Hi everyone, I would like to create a 2x5 matrix. Row 1 will be the sin(x) and Row 2 the cos(x). Each column will be the values of x being 0, 90, 180, 270, 360.
I do not seem to get it right. Can anyone please direct me to my mistake? I do not need a solution to my assignment, I just need some guidance.
for j=0:4
j=j+1
for i=0:90:360
Y(1,j)=sin(i)
Y(2,j)=cos(i)
end
end
Any help is appreciated.

 채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 9월 18일
편집: Mohammad Abouali 2014년 9월 18일

0 개 추천

Theta=[0, 90, 180, 270, 360];
Y=zeros(2,numel(Theta))
Y(1,:)=sind(Theta);
Y(2,:)=cosd(Theta);
NOTE the "d" after sin and cos function.

댓글 수: 2

Y = [sind(Theta);cosd(Theta)];
Duffy Duck
Duffy Duck 2014년 9월 18일
Thank you very much !

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2014년 9월 18일

0 개 추천

Note that
  • Indexing in ML starts at 1
  • You should rarely change the iterator inside the loop
  • sin and cos take radians, rather than degrees
  • do you really need a double loop?
Angles = [0 90 180 270] % angles in degrees
N = numel(Angles)
Y = nan(N,2) % pre allocation
for j=1:N
tmp = Angles(j) * (pi/180)
Y(j,1) = sin(tmp)
Y(j,2) = cos(tmp)
end
Note that you can vectorise this.

댓글 수: 3

Joseph Cheng
Joseph Cheng 2014년 9월 18일
some additional help is that you can use sind() and cosd() to stay with degrees and not convert to radians. And if you want 2x5 (2 rows and 5 columns) then switch the j and 1/2 in the Y(j,#) around so it reads Y( row 1, column j) = sin(tmp);
Duffy Duck
Duffy Duck 2014년 9월 18일
Thank you very much !
Joseph Cheng
Joseph Cheng 2014년 9월 18일
also there is no need to do this in a loop. the sin and cos functions will accept arrays and perform the sin and cos on each index. so similarly how Jos has Angles you can go cos(angles) and have the cos of each individual index as a return.

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2014년 9월 18일

댓글:

2014년 9월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by