# How to operate on spans of rows in a matrix?

I have a [2001,2] matrix of (x,y) values, but the number of rows could vary.

I would like to go through the entire matrix, and divide each of the y values by a certain number, depending on their x value.

For example, for x values from 600-700, I would like to divide the corresponding y value by 10. For x values from 700-800, I would like to divide the corresponding y value by 20.

My idea was a for loop that looped the entire matrix, and then nested "if" statements that said

if data[[n, 1]] < 700, data[[n, 2]] = data[[n, 2]]/10

if data[[n, 1]] >= 700 && data[[n, 1]] <800, data[[n, 2]] = data[[n, 2]]/20


However, I can't even figure out how to determine the number of rows in a matrix to ensure I loop the correct 2001 times (I want my code to work for any length).

Dimensions[data] doesn't help and Length[Dimensions[data]] doesn't do it either and neither does Length[Dimensions[Transpose[data]]].

• I don't see why Dimensions wouldn't work? What is your output thereof? – Feyre Sep 30 '16 at 18:10

Define your function that depends on $x$ as a Piecewise:

div[x_] :=
Piecewise[{{1, x < 600}, {10, 700 > x >= 600}, {20,
800 > x >= 700}, {1, x >= 800}}];


Now apply it to your matrix, leaving $x$ the same and dividing $y$ by $div(x)$

a = RandomReal[{0, 1000}, {2001, 2}];
{#1, #2/div[#1]} & @@@ a


Do not use loops, more on that in loop alternatives.

Take a matrix:

m = RandomReal[{-1, 1}, {50, 2}];


divlist is the list in which you set the amount you want each row to be divided by.

divlist = Range^2 + 4;


{{0.122485, 0.113589, 0.0614795, ..., -0.000421888, 0.000414203, -0.000404009, 0.000252482},

{0.181547, -0.0939199, -0.00331032, ..., -0.0000740111, -0.000279882, -0.000368139}}

data = RandomInteger[{500., 800.}, {10, 2}]


{{583, 614}, {518, 744}, {731, 732}, {783, 593}, {693, 742}, {658, 601}, {552, 741}, {741, 569}, {522, 524}, {705, 533}}

Table[If[600 <= data[[i, 1]] < 700, data[[i, 2]] = data[[i, 2]]/10,
If[700 <= data[[i, 1]] < 800, data[[i, 2]] = data[[i, 2]]/20],
data[[i, 2]] = data[[i, 2]]], {i, 1, Length@data}];

N@data


{{583., 614.}, {518., 744.}, {731., 1.83}, {783., 1.4825}, {693., 7.42}, {658., 6.01}, {552., 741.}, {741., 1.4225}, {522., 524.}, {705., 1.3325}}