Storage results in an array

1 vue (au cours des 30 derniers jours)
Chuming Wei
Chuming Wei le 21 Oct 2021
Réponse apportée : Chunru le 21 Oct 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

Réponse acceptée

KSSV
KSSV le 21 Oct 2021
Modifié(e) : KSSV le 21 Oct 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

Plus de réponses (2)

Akira Agata
Akira Agata le 21 Oct 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 le 21 Oct 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by