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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by