Creating a matrix using loop for and if
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi In workspace I have matrix A 601x1 double created by Simulink simulation. Now i want to create new matrix B also 601x1 double more less like this. I want the new matrix B be the same as A when its values are smaller than 360, but when the values are greater or equal 360 i want to substract 360. I dont know how to create this B matrix like that. Below is something i used to try but failed.
for k=A(1):1:A(end)
if A < 360
B=A
elseif A >=360
B=A-360
end
end
댓글 수: 0
채택된 답변
Guillaume
2016년 8월 24일
A loop is completely unnecessary:
B = A;
B(B>360) = B(B>360) - 360;
Using a loop, this would have been the proper syntax:
B = zeros(size(A)); %always preallocate
for idx = 1 : numel(A) %your loop indexing was completely wrong
if A(idx) < 360
B(idx) = A(idx); %and of course, you must use the index somewhere
else %no need for elseif A(idx)>=360, if the 1st condition wasn't true, then the other one obviously is
B(idx) = A(idx) - 360;
end
end
Note that if all you want to do is make sure that values in B are between 0 and 360, then:
B = mod(A, 360);
is even simpler.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!