why my conditional function is not what I expected?

1 visualización (últimos 30 días)
2NOR_Kh
2NOR_Kh el 8 de Sept. de 2022
Comentada: 2NOR_Kh el 8 de Sept. de 2022
I have this question to solve:
this is my program:
close all
clear all
x = -3:0.5:3;
y = -3:0.5:3;
[X,Y] = meshgrid(x,y);
[m,n]=size(X);
f=zeros(m,n);
if X>=0 & X.^2+Y.^2<4
f=ones(m,n);
elseif (-2 < X) & (X < 0) & abs(Y)<2
f=1/2*ones(m,n);
else
f=zeros(m,n);;
end
surfl(X,Y,f)
I don't exactly which part of my program is wrong that I can't see that 1/2 in my function in this plot.

Respuesta aceptada

David Hill
David Hill el 8 de Sept. de 2022
[x,y] = meshgrid(-3:0.1:3);
f=zeros(size(x));
f(x>=0&(x.^2+y.^2)<4)=1;
f(x>-2&x<0&abs(y)<2)=.5;
surfl(x,y,f)

Más respuestas (2)

Steven Lord
Steven Lord el 8 de Sept. de 2022
if X>=0 & X^2+Y^2<4
From the documentation for the if keyword: "if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric)."
Since X and Y are not scalars, the expression for this if statement is true only if all the elements of X are greater than or equal to 0 and all the elements of X^2+Y^2 are less than 4. If even one pair of elements of X and Y doesn't satisfy that condition, the if statement is not satisfied.
You probably want to use logical indexing and the array power operator .^ rather than the matrix power operator ^ which will give a different answer.

Mathieu NOE
Mathieu NOE el 8 de Sept. de 2022
hello
this works better :)
close all
clear all
x = -3:0.1:3;
y = -3:0.1:3;
[X,Y] = meshgrid(x,y);
[m,n]=size(X);
f=zeros(m,n);
% condition 1
ind1 = (X>=0) & (X.^2+Y.^2<4); % NB : dots !! .^
f(ind1) = 1 ;
% condition 2
ind2 = (-2 < X) & (X < 0) & abs(Y)<2 ;
f(ind2) = 1/2 ;
surfl(X,Y,f)
xlabel('X');
ylabel('Y');

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by