How do I compare values within a for loop using if/else?

53 views (last 30 days)
I am trying to compare the values of Vx and Vy as they are generated and display a statement based on whether Vx is greather than, less than, or equal to Vy. The first value returns correctly as equal, but the rest of the values return as X > Y, even though many should return as X < Y.
clc
clear all
close all
x=0:5:20;
y=0:10:40;
z=0:20:80;
[X,Y,Z]=meshgrid(x,y,z);
Vx=zeros(5,5,5);
Vy=zeros(5,5,5);
Vz=zeros(5,5,5);
for i=1:length(x)
for j=1:length(y)
for k=1:length(z)
Vx(i,j,k)=(((i-1)*5).^2)+(((j-1)*10).^2)+(((k-1)*20).^2);
Vy(i,j,k)=2*((i-1)*5)*((j-1)*10)*((k-1)*20);
Vz(i,j,k)=((i-1)*5)+((j-1)*10)+(2*((k-1)*20));
if Vx==Vy
disp('X = Y')
elseif Vx<Vy
disp('X < Y')
else
disp('X > Y')
end
end
end
end
figure;
quiver3(X,Y,Z,Vx,Vy,Vz)
xlabel('X Axis')
ylabel('Y Axis')
zlabel('Z Axis')
set(gca,'FontSize',12)
set(gca,'ZDir','reverse')

Accepted Answer

Voss
Voss on 5 Sep 2022
Seems like you want to compare one element of Vx and Vy at a time:
if Vx(i,j,k) == Vy(i,j,k)
disp('X = Y')
elseif Vx(i,j,k) < Vy(i,j,k)
disp('X < Y')
else
disp('X > Y')
end
When you use a non-scalar array in a comparison, such as Vx == Vy, the result is considered true only if it's true for all elements.

More Answers (1)

Walter Roberson
Walter Roberson on 5 Sep 2022
Vx(i,j,k)=(((i-1)*5).^2)+(((j-1)*10).^2)+(((k-1)*20).^2);
Vy(i,j,k)=2*((i-1)*5)*((j-1)*10)*((k-1)*20);
Vz(i,j,k)=((i-1)*5)+((j-1)*10)+(2*((k-1)*20));
Those statements are building arrays.
if Vx==Vy
That statement is comparing all of Vx to all of Vy. In MATLAB, an "if" is considered true if all of the values computed are non-zero, same as if you hard written
if all(Vx(:)==Vy(:))
If even a single element of Vx is not equal to its corresponding Vy then the test would be considered false.
Perhaps you should only be comparing the array elements you just computed.
  2 Comments
Timothy Nix
Timothy Nix on 5 Sep 2022
Ah I can see how that would cause an issue now. I will keep that in mind in the future, thank you!

Sign in to comment.

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by