why my conditional function is not what I expected?
2 次查看(过去 30 天)
显示 更早的评论
I have this question to solve:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1120060/image.png)
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.
0 个评论
采纳的回答
David Hill
2022-9-8
[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)
更多回答(2 个)
Steven Lord
2022-9-8
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.
0 个评论
Mathieu NOE
2022-9-8
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');
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Array and Matrix Mathematics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!