How to create an mxn matrix with a for-loop
Afficher commentaires plus anciens
Hello all,
I would like to display (x(i),y(j)) in separate columns according to the x(i)'s.
i.e.:
(0,0) (1,0) (2,0)
(0,1) (1,1) (2,1)
(0,2) (1,2) (2,2), etc.
I am currently using a nested for-loop to calculate all (x(i),y(j)) as follows:
for i = 1:3
a = i-1;
for j = 1:3
b = j-1;
X = [a b];
disp(X);
end
end
I get the output as follows:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
I tried using reshape to display the output as above, however in fiddling with the program, I discovered that MATLAB considers each line of output to be a separate 1x2 matrix. Do you have any suggestions as to how to get MATLAB to recognize the outputs as a 9x2 matrix? This is an extremely scaled-down version of what I need the program to do.
Thank you!!
4 commentaires
Stephen23
le 28 Juil 2016
@Dominique Brasee: why waste time and space writing nested loops? MATLAB is a high-level language, so you don't need to rely on loops to solve all of your tasks (see dpb's comment how).
>> permn(0:2,2)
ans =
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
dpb
le 28 Juil 2016
Nice find,Stephen...I should check FEX more often, meself... :)
ABISHAI JOY
le 16 Fév 2020
How will you put cos (x+y) in to a matrix and it should generate random values with x, y between [0,2pi].
dpb
le 16 Fév 2020
Use rand(), maybe???
Réponse acceptée
Plus de réponses (3)
Lam Nguyen Van
le 10 Mar 2020
1 vote
Hi,
I want to creat matrices automatically with for loop in Matlab?
phi1=30; phi2=45; phi3=90;
After running the code I want to have a matric A with the following elements:
A=[sin(phi1) cos(phi1) sin(phi1)*cos(phi1);
sin(phi2) cos(phi2) sin(phi2)*cos(phi2);
sin(phi3) cos(phi3) sin(phi3)*cos(phi3);]
1 commentaire
Lam Nguyen Van
le 16 Avr 2020
0 votes
https://www.mathworks.com/matlabcentral/answers/372036-can-you-create-a-matrix-using-a-for-loop?s_tid=mlc_ans_email_view&utm_source=zalo&utm_medium=zalo&utm_campaign=zalo&zarsrc=1303
Lam Nguyen Van
le 17 Avr 2020
0 votes
clear;
phi=[30, 45, 90];
n=length(phi);
A=zeros(n,3);
for i=1:n
[d]= ham_luong_giac (phi(i));
A(i,:)=[d];
end
A
function [xuat] = ham_luong_giac (phi)
a1=sin(phi);
a2=cos(phi);
a3=sin(phi).*cos(phi);
xuat= [a1, a2, a3];
end
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!