Specifying the iteration range for 'for' loops

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?

 Respuesta aceptada

Stephen23
Stephen23 el 1 de Feb. de 2019
Editada: Stephen23 el 1 de Feb. de 2019

2 votos

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

4 comentarios

Since R2016b:
X = (1:size(M, 2)) >= V(:); %no need for bsxfun
Sam Smith
Sam Smith el 1 de Feb. de 2019
Thanks, good work. How do I perform an operation, say an assignment, where I only want the assignment to take place where the X matrix is a 1.
Stephen23
Stephen23 el 1 de Feb. de 2019
Editada: Stephen23 el 1 de Feb. de 2019
"How do I perform an operation, say an assignment, where I only want the assignment to take place where the X matrix is a 1. "
Possibly you can just X as an index. If that does not do what you want, please show a simple example with all input and output matrices, and explain in more detail what you are trying to achieve.
Thanks for your help. Say I have a 6-by-360 matrix, A. I want B to equal A, but only on some entries. For most rows, B can equal A from 1:360, but for some rows, I want B to equal A only from 2:360 (say row 2) or 4:360 (row 5) say (because entries before then are Inf or not relevant).
I guess something like
for i=1:size(A,1)
for j=1:size(A,2)
if X(i,j)==1
B(i,j)=A(i,j)
end
end
end

Iniciar sesión para comentar.

Más respuestas (1)

Cris LaPierre
Cris LaPierre el 1 de Feb. de 2019

0 votos

Are those arbiltrary choices of the columns to sum or is there a pattern?
If doing this with a for loop, ideally you are looping through each row, but the exact same code is executed for each row. You'd have to code the pattern into the code that executes. If you can't be more precise on how the columns are selected, I'm afraid you'd either have to preprocess your data by zeroing the data you don't want to sum, or you'd have to manually sum each row.

1 comentario

Stephen23
Stephen23 el 1 de Feb. de 2019
Sam Smith's "Answer" moved here:
It's something I would like to manually choose.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 1 de Feb. de 2019

Comentada:

el 1 de Feb. de 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by