Storage results in an array

2 visualizaciones (últimos 30 días)
Chuming Wei
Chuming Wei el 21 de Oct. de 2021
Respondida: Chunru el 21 de Oct. de 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

Respuesta aceptada

KSSV
KSSV el 21 de Oct. de 2021
Editada: KSSV el 21 de Oct. de 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

Más respuestas (2)

Akira Agata
Akira Agata el 21 de Oct. de 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 el 21 de Oct. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by