how to split a forloop into columns

I have written a code which contains a for loop but I need it to be seperated into columns. This is the code, however I would like each value of N to be a new column. Is there a way of doing that?
for N=1:12;
for m=1:12;
if mod(N, m)==0
disp '1'
else disp '0'
end
end
end

 採用された回答

Star Strider
Star Strider 2016 年 1 月 6 日

0 投票

I am not certain what you want to do. See if this produces what you want:
N = 1:12;
m = 1:12;
[Nmat,mmat] = meshgrid(N,m);
modmat = mod(Nmat,mmat)==0;
Result = [Nmat(:) mmat(:) modmat(:)];

8 件のコメント

A123456
A123456 2016 年 1 月 6 日
I am trying to make it so that it forms a matrix, I tried inputting that but nothing changed
Star Strider
Star Strider 2016 年 1 月 6 日
I’m not certain what you want. My ‘Result’ matrix has the values of ‘N’ in the first column, values of ‘m’ in the second, and the result of the corresponding mod operations on them in the third. That’s what I thought you meant by ‘separated into columns’.
Does reshaping it this way get closer to what you want:
Result3 = reshape(Result, size(N,2), size(m,2), []);
Here, ‘N’ is on the first ‘page’, ‘m’ the second, and the mod result the third. You can address it as you wish. For example to get the result for N=1:
N_1 = reshape(Result3(:,1,:), 12, 3)
N_1 =
1 1 1
1 2 0
1 3 0
1 4 0
1 5 0
1 6 0
1 7 0
1 8 0
1 9 0
1 10 0
1 11 0
1 12 0
For N=2, this becomes:
N_2 = reshape(Result3(:,2,:), 12, 3)
and so for the rest.
A123456
A123456 2016 年 1 月 6 日
Yes it does, thanks. Sorry but I forgot to mention I only need the mod result displayed, not the columns N and m.
Star Strider
Star Strider 2016 年 1 月 6 日
OK. If you only want a matrix of the mod operation, then that is just the ‘modmat’ matrix. You can omit the rest of the code.
A123456
A123456 2016 年 1 月 6 日
Could you write it out for me as I'm a bit confused on what to keep and what to omit in the code?
Star Strider
Star Strider 2016 年 1 月 6 日
I’ll be happy to!
If you only need the ‘modmat’ matrix, this is all you need of my code:
N = 1:12;
m = 1:12;
[Nmat,mmat] = meshgrid(N,m);
Result = mod(Nmat,mmat)==0;
I renamed it to be ‘Result’, since it seems to be what you want.
A123456
A123456 2016 年 1 月 6 日
Thanks for that, your help was great!
Star Strider
Star Strider 2016 年 1 月 6 日
As always, my pleasure!

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by