Storage results in an array

1 view (last 30 days)
Chuming Wei
Chuming Wei on 21 Oct 2021
Answered: Chunru on 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

Accepted Answer

KSSV
KSSV on 21 Oct 2021
Edited: KSSV on 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

More Answers (2)

Akira Agata
Akira Agata on 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 on 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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!