why my conditional function is not what I expected?
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 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에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!