make loop if two variable (x and y) present calculate value for (x1 and y1) and store separate name for same formula another calculate for (x2,y2) and store by separate?

5 次查看(过去 30 天)
x = [1 2 3 4 5];
y= [ 8 3 2 1 6];
z = exp(x)+x*y^3 +y;
calculate it and store as
z1(x1,y1)
z2(x2,y2)
...so on..
and
plot(x1,z1)
hold on
plot(x2,z2)
hold on
plot(x3,z3)
.....
hold off

回答(1 个)

VBBV
VBBV 2023-4-10
编辑:VBBV 2023-4-10
x = [1 2 3 4 5];
y= [ 8 3 2 1 6];
% vectorize the equation (easier approach)
z = exp(x)+x.*y.^3 +y;
% using for loop
hold on
for k = 1:numel(z)
z(k) = exp(x(k))+x(k)*y(k)^3 +y(k);
plot(x(k),z(k),'ro','MarkerSize',10,'linewidth',2);
end
figure
plot(x,z)
  5 个评论
VBBV
VBBV 2023-4-10
Can this be made in a loop?
Yes, that i what has been shown in below code
x = [1 2 3 4 5];
y= [ 8 3 2 1 6];
hold on
for k = 1:numel(x)
z(k) = exp(x(k))+x(k)*y(k)^3 +y(k); % as an array
plot(x(k),z(k),'ro','MarkerSize',10,'linewidth',2);
end
figure
hold on
for k = 1:numel(x)
% without array (only scalar z !) as you wanted
z = exp(x(k))+x(k)*y(k)^3 +y(k); % z will have only last value at end of loop !!!
plot(x(k),z,'bo','MarkerSize',10,'linewidth',2);
end

请先登录,再进行评论。

类别

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

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by