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!