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
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?
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 Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2016년 1월 6일

댓글:

2016년 1월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by