Fixing loop values while plotting

2 次查看(过去 30 天)
Hello All,
I have been practicing matlab for fun for sometime now and I am getting into plotting data structures at the moment. I have been trying to "fix" certain loop values while plotting but I have been having a hard time getting this to work. In the code below, I would like to plot all the 'b" values for y=1 and z=1 while x=1:3. I can easily do this by fixing one of the variables but I currently can not fix y and z at the same time. Please see my simple code below. Any advice would be greatly appreciated! Thank you!
vals.y=[];
vals.x=[];
vals.b=[];
vals.z=[];
for z = 1:3;
for y = 1:3;
for x=1:3;
b = x*y*z;
vals.y(end+1)=y;
vals.x(end+1)=x;
vals.b(end+1)=b;
vals.z(end+1)=z;
end
end
end
plot(vals.b(vals.y==1),vals.x(vals.y==1));
%plot(vals.b(vals.y==1 & vals.z==1,vals.x(vals.y==1 & vals.z==1)); - Would Like to this
% to this

回答(1 个)

Shunichi Kusano
Shunichi Kusano 2019-4-24
Your code almost works. You need a closing parenthesis.
plot(vals.b(vals.y==1 & vals.z==1,vals.x(vals.y==1 & vals.z==1)) % your code
plot(vals.b(vals.y==1 & vals.z==1),vals.x(vals.y==1 & vals.z==1)) % corrected code
And one suggestion. It's a good practice that you do not use for-loop, if you can. In this case, The following code is prefarable. This is easier to write and faster to calculate.
[vals.x, vals.y, vals.z] = meshgrid(1:3);
b = vals.x .* vals.y .* vals.z;
  1 个评论
Fabiano Da Mota
Fabiano Da Mota 2019-4-24
Hello Shunichi,
Thank you very much! I have been trying different things for a couple of hours and the solution was simpler than I expected. Thank you again.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by