Creating a matrix using loop for and if
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Jakub F
am 24 Aug. 2016
Kommentiert: Jakub F
am 24 Aug. 2016
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 Kommentare
Akzeptierte Antwort
Guillaume
am 24 Aug. 2016
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!