Storage results in an array

2 Ansichten (letzte 30 Tage)
Chuming Wei
Chuming Wei am 21 Okt. 2021
Beantwortet: Chunru am 21 Okt. 2021
Hello
I want storage results in an array
for example
I have
for x=[2,3,4,5,6];
if x>4
y=x^2
else
y=x+2
end
end
Then I got
y =
4
y =
5
y =
6
y =
25
y =
36
I want y=[4,5,6,25,36]
Thank you

Akzeptierte Antwort

KSSV
KSSV am 21 Okt. 2021
Bearbeitet: KSSV am 21 Okt. 2021
x=[2,3,4,5,6];
y=zeros(size(x)) ;
for i = 1:length(x)
if x(i)>4
y(i)=x(i)^2
else
y(i)=x(i)+2
end
end
No loop is needed to achieve this:
x=[2,3,4,5,6];
y=x+2;
y(x>4)=x(x>4).^2 ;
y

Weitere Antworten (2)

Akira Agata
Akira Agata am 21 Okt. 2021
Instead of uisng for-loop, you can do this task by vectorizing, like:
x = [2, 3, 4, 5, 6];
y = x + 2;
idx = x > 4;
y(idx) = x(idx).^2;
disp(y)
4 5 6 25 36

Chunru
Chunru am 21 Okt. 2021
% Without loop
x=[2,3,4,5,6];
y=x;
y(x>4)=x(x>4).^2;
y(x<=4)=x(x<=4)+2
y = 1×5
4 5 6 25 36
% With loop
x = [2,3,4,5,6];
y = zeros(size(x));
for i=1:length(x)
if x(i)>4
y(i)=x(i)^2;
else
y(i)=x(i)+2;
end
end
y
y = 1×5
4 5 6 25 36

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!

Translated by