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 件のコメント

Guillaume
Guillaume 2019 年 2 月 1 日
Since R2016b:
X = (1:size(M, 2)) >= V(:); %no need for bsxfun
Sam Smith
Sam Smith 2019 年 2 月 1 日
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.
Sam Smith
Sam Smith 2019 年 2 月 1 日
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 件のコメント

Stephen23
Stephen23 2019 年 2 月 1 日
Sam Smith's "Answer" moved here:
It's something I would like to manually choose.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops 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