MATLAB Answers

Element wise conditional evaluation of a function over a meshgrid

15 ビュー (過去 30 日間)
Adamya Goyal
Adamya Goyal 2020 年 4 月 9 日
コメント済み: James Browne 2020 年 4 月 10 日
I created a 2-D mesh using meshgrid. Now, I want to evaluate a function over this mesh based on the elements of mesh i.e., if the mesh elements are equal then evaluate expression1 else evaluate expression2.
a=linspace(1,2,2);
b=linspace(1,3,3);
[A,B]=meshgrid(a,b)
fact(A,B,0.1)
function f = fact(m,n,lam)
if m==n
f=m.*(n+2)+lam;
else
f=0;
end
end
The above just gives me the matrices A and B and 0 from the else statement. I want it to compare the elements of "m" and "n" and evaluate the "if" part if they are the same. I tried using bsxfun(@eq,m,n) instead of m==n. It gives the same result, 0 from the else part. Below is the output.
A =
1 2
1 2
1 2
B =
1 1
2 2
3 3
ans =
0
Instead, evaluating the following code (no if statement) over the mesh does give me the expected result of the function values over the entire mesh.
a=linspace(1,2,2);
b=linspace(1,3,3);
[A,B]=meshgrid(a,b)
fact(A,B,0.1)
function f = fact(m,n,lam)
f=m.*(n+2)+lam;
end
gives
A =
1 2
1 2
1 2
B =
1 1
2 2
3 3
ans =
3.1000 6.1000
4.1000 8.1000
5.1000 10.1000
The output I am looking for should look like
3.1000 0
0 8.1000
0 0

  0 件のコメント

サインインしてコメントする。

採用された回答

Matt J
Matt J 2020 年 4 月 10 日
編集済み: Matt J 2020 年 4 月 10 日
f = (A==B) .* (A.*(B+2)+lam);

  3 件のコメント

Adamya Goyal
Adamya Goyal 2020 年 4 月 10 日
Wow. Thank you! This looks like magic. ??
Matt J
Matt J 2020 年 4 月 10 日
You're welcome, but please Accept-click the answer to indicate that it worked.
James Browne
James Browne 2020 年 4 月 10 日
That is pretty awesome! Nice work!

サインインしてコメントする。

その他の回答 (1 件)

James Browne
James Browne 2020 年 4 月 10 日
Hello, I believe that I have developed a solution for you:
a=linspace(1,2,2);
b=linspace(1,3,3);
[A,B] = meshgrid(a,b)
fact(A,B,0.1)
function f = fact(m,n,lam)
f = zeros(size(n,1), size(n,2));
for i = 1:size(n,1)
for j = 1:size(n,2)
if m(i,j) == n(i,j)
f(i,j) = m(i,j)*(n(i,j)+2)+lam;
else
f(i,j)=0;
end
end
end
end
Hope this at least helps =)

  1 件のコメント

Adamya Goyal
Adamya Goyal 2020 年 4 月 10 日
Yes. Thank you so much. But, I want to avoid using loops and keep it "vectorized" if possible. Because the mesh I am going to use this for is going to be huge (~10000x10000 or larger).

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by