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

 Réponse acceptée

Star Strider
Star Strider le 6 Jan 2016
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 commentaires

A123456
A123456 le 6 Jan 2016
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 le 6 Jan 2016
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 le 6 Jan 2016
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 le 6 Jan 2016
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 le 6 Jan 2016
Thanks for that, your help was great!
Star Strider
Star Strider le 6 Jan 2016
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by