How to combining outputs into one array?

Hello everyone,
I am a newbie to Matlab and I am struggling. I'm hoping that the output Y will turn out as:
Y = 74.48 80.87 84.06 89.53 92.79 94.82 96.16 97.07
BUT, my code outputs Y separately, one at a time.
MY CODE:
Y = [];
for X = [40,46,50,60,70,80,90,100]
Y = 100*X.^2.65/(X.^2.65+26.7^2.65)
end
Can someone PLEASE help me.
Thank you!

回答(2 个)

When you are iterating over values that are not simple consequative integers starting from 1, then it is often a good idea to create a list of values to be processed, and then iterate an index over 1 to the size of the list, extracting the relevant entry of the list to use in the computations.
Y = [];
Xvals = [40,46,50,60,70,80,90,100];
Y = zeros(size(Xvals));
for K = 1 : numel(Xvals);
X = Xvals(K);
Y(K) = 100*X.^2.65/(X.^2.65+26.7^2.65);
end
Y
Y = 1×8
74.4820 80.8693 84.0574 89.5262 92.7852 94.8241 96.1585 97.0669
Rather than using a loop, the simpler MATLAB approach:
X = [40,46,50,60,70,80,90,100];
Y = 100*X.^2.65./(X.^2.65+26.7^2.65)
Y = 1×8
74.4820 80.8693 84.0574 89.5262 92.7852 94.8241 96.1585 97.0669

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2023a

提问:

2023-9-9

移动:

2023-9-9

Community Treasure Hunt

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

Start Hunting!

Translated by