Creating a matrix using loop for and if

조회 수: 1 (최근 30일)
Jakub F
Jakub F 2016년 8월 24일
댓글: Jakub F 2016년 8월 24일
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

채택된 답변

Guillaume
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.
  댓글 수: 1
Jakub F
Jakub F 2016년 8월 24일
Well, I'll be damned, this
B = mod(A, 360)
is all i needed :) thanks.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by