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

60 visualizzazioni (ultimi 30 giorni)
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')

Risposta accettata

Voss
Voss il 5 Set 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.

Più risposte (1)

Walter Roberson
Walter Roberson il 5 Set 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 Commenti
Walter Roberson
Walter Roberson il 5 Set 2022
Also, remember that the == operator between the same data type is bit-for-bit exact comparison (with the exception that negative 0 is considered to compare equal to 0, and nan is not equal to nan). See for example
format long g
A = 0.3 - 0.2
A =
0.1
B = 0.1
B =
0.1
A == B
ans = logical
0
A - B
ans =
-2.77555756156289e-17
The same algebraic value calculated two different ways can end up rounded differently. Using == might not be appropriate. Consider comparing with tolerance, such as using ismembertol
Timothy Nix
Timothy Nix il 5 Set 2022
Ah I can see how that would cause an issue now. I will keep that in mind in the future, thank you!

Accedi per commentare.

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by