MATLAB: Specifying the iteration range for ‘for’ loops

for loop

Say I have a matrix of size 5-by-5. I want to sum the elements in the rows, but I don't want to sum from the first column all the time, I want to choose from which column to sum from for any row. So say first row I want to sum 2:5, 2nd row 1:5, 3rd row 4:5, etc. How do I do this?

Best Answer

There is no need to use a loop:
>> M = randi(9,5,5) % random 5x5 matrix
M =
7 1 5 6 6
7 4 8 2 5
7 4 4 1 7
7 3 7 6 4
8 8 6 9 1
>> V = [2,1,4,4,3]; % first column
>> X = bsxfun(@ge,1:5,V(:))
X =
0 1 1 1 1
1 1 1 1 1
0 0 0 1 1
0 0 0 1 1
0 0 1 1 1
>> sum(M.*X,2)
ans =
18
26
8
10
16