I just learned about Matlab's ability to use matrices as arguments to a for loop;
This displays the columns of the matrix A
A = magic(5)
for n = A
disp(n)
end
I was wondering if it is possible to obtain a sequential index into a loop like this. ie. if I want to print the column number along with the column itself, can I continue with the form above or would I need to revert to a more typical form like
A = magic(5)
for jj = 1:length(A)
disp(['Column #',num2str(jj)])
disp(A(:,jj))
end

 採用された回答

Walter Roberson
Walter Roberson 2012 年 9 月 24 日

0 投票

You would need the more traditional form. There is no way to query which iteration number you are on.

その他の回答 (2 件)

Matt Fig
Matt Fig 2012 年 9 月 24 日

1 投票

A = magic(5)
cnt = 1;
for jj = A
disp(['Column #' num2str(cnt)])
disp(jj),
cnt = cnt+1;
end

4 件のコメント

Ravi
Ravi 2012 年 9 月 24 日
Thanks for this. Unfortunately, it looks like I can only mark one answer as accepted...
Matt Fig
Matt Fig 2012 年 9 月 24 日
編集済み: Matt Fig 2012 年 9 月 24 日
Walter, did you look closely at the code? I ran it, and it does exactly what Ravi asked for...
Column #1
17
23
4
10
11
Column #2
24
5
6
12
18
Column #3
1
7
13
19
25
Column #4
8
14
20
21
2
Column #5
15
16
22
3
9
Walter Roberson
Walter Roberson 2012 年 9 月 24 日
Oh... yes, you are right, I had forgotten that it went by columns when matrices are used. blush
Ravi
Ravi 2012 年 9 月 24 日
I see... Backstory is that I was thinking about rewriting some existing code with for loops using the matrix approach for potential performance improvements. I did some quick tests and both methods take almost identical times. I can see the matrix approach being helpful down the line. Kind of like having a 'foreach' command.

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

Shadow
Shadow 2024 年 4 月 2 日

0 投票

enumer = @(my_array) cell2mat(arrayfun(@(x,idx) struct("cargo",x,"idx",idx), my_array(:).', 1:numel(my_array(:).'),UniformOutput=false));
data = rand(5,4)
s=size(data);
for elem = enumer(data)
[row,col] = ind2sub(s,elem.idx);
disp("Element " + string(elem.cargo) + " with index " + string(elem.idx) + " at location " + string(row) + "," + string(col))
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2012 年 9 月 24 日

回答済み:

2024 年 4 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by