Can you create a matrix using a for loop

Is possible to create a matrix by just using for loops Thanks

댓글 수: 2

what type of matrix? can you please provide more details regarding this query?
Stephen23
Stephen23 2017년 12월 9일
"Is possible to create a matrix by just using for loops"
Yes.

댓글을 달려면 로그인하십시오.

답변 (2개)

Amy
Amy 2017년 12월 11일

0 개 추천

Look at the first example in the documentation for 'for': https://www.mathworks.com/help/matlab/ref/for.html
Lam Nguyen Van
Lam Nguyen Van 2020년 3월 10일

0 개 추천

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);]

댓글 수: 3

lengthy code for query
phi1=30; phi2=45; phi3=90;
rows= 3;
cols=3;
A= zeros(3);
row_num=1;
col_num =1;
for i = 1: 3
if row_num ==1
A(1,i)= sin(phi1);
col_num =col_num+1;
if col_num ==2
A(1,col_num)= cos(phi1);
col_num =col_num+1;
end
if col_num ==3
A(1,col_num)= sin(phi1)*cos(phi1);
col_num =col_num+1;
end
row_num=row_num+1;
end
col_num=1;
if row_num ==2
A(2,i)= sin(phi2);
col_num =col_num+1;
if col_num ==2
A(2,col_num)= cos(phi2);
col_num =col_num+1;
end
if col_num ==3
A(2,col_num)= sin(phi2)*cos(phi2);
col_num =col_num+1;
end
row_num=row_num+1;
end
col_num=1;
if row_num ==3
A(3,i)= sin(phi3);
col_num =col_num+1;
if col_num ==2
A(3,col_num)= cos(phi3);
col_num =col_num+1;
end
if col_num ==3
A(3,col_num)= sin(phi3)*cos(phi3);
col_num =col_num+1;
end
row_num=row_num+1;
end
end
Lam Nguyen Van
Lam Nguyen Van 2020년 3월 10일
Thanks!
I want to use
for i=1:3
for j=1:3
A(i,j)=...;
end
end
I want shorter code.
Lam Nguyen Van
Lam Nguyen Van 2020년 3월 11일
I did it. I used for loop and function.
phi=[30, 45, 90];
n=length(phi);
[e]=xuat_vecto(phi1);
A=zeros(n,3);
for i=1:n
[d]= xuat_vecto (phi(i));
A(i,:)=[d];
end
A
function [e]=xuat_vecto(alpha)
[a, b, c]=ham_luong_giac (alpha);
e=[a, b, c];
end
function [a1, a2, a3] = ham_luong_giac (phi)
a1=sin(phi);
a2=cos(phi);
a3=sin(phi)*cos(phi);
xuat= [a1, a2, a3];
end

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 12월 9일

댓글:

2020년 3월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by