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
采纳的回答
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 个评论
I am trying to make it so that it forms a matrix, I tried inputting that but nothing changed
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.
Yes it does, thanks. Sorry but I forgot to mention I only need the mod result displayed, not the columns N and m.
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.
Could you write it out for me as I'm a bit confused on what to keep and what to omit in the code?
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.
Thanks for that, your help was great!
As always, my pleasure!
更多回答(0 个)
类别
在 帮助中心 和 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!选择网站
选择网站以获取翻译的可用内容,以及查看当地活动和优惠。根据您的位置,我们建议您选择:。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
