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
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.
"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 个)

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.

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by