Fixing loop values while plotting

2 ビュー (過去 30 日間)
Fabiano Da Mota
Fabiano Da Mota 2019 年 4 月 23 日
コメント済み: Fabiano Da Mota 2019 年 4 月 24 日
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 Center および File ExchangeCreating 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