why my conditional function is not what I expected?

2 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by