why my conditional function is not what I expected?

조회 수: 1 (최근 30일)
2NOR_Kh
2NOR_Kh 2022년 9월 8일
댓글: 2NOR_Kh 2022년 9월 8일
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.

채택된 답변

David Hill
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
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.

Mathieu NOE
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');

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by