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 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