Storage results in an array

1 次查看(过去 30 天)
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

采纳的回答

KSSV
KSSV 2021-10-21
编辑:KSSV 2021-10-21
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

更多回答(2 个)

Akira Agata
Akira Agata 2021-10-21
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 2021-10-21
% 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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by