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?

 채택된 답변

Stephen23
Stephen23 2019년 2월 1일
편집: Stephen23 2019년 2월 1일

2 개 추천

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

Since R2016b:
X = (1:size(M, 2)) >= V(:); %no need for bsxfun
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 2019년 2월 1일
편집: Stephen23 2019년 2월 1일
"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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Cris LaPierre
Cris LaPierre 2019년 2월 1일

0 개 추천

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

Sam Smith's "Answer" moved here:
It's something I would like to manually choose.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2019년 2월 1일

댓글:

2019년 2월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by