Not getting the expected size matrix from evaluating a function handle that is equal to zero
이전 댓글 표시
h = @(x,y) 0
[X, Y] = meshgrid(linspace(0, 2, 10));
Z = h(X,Y);
X and Y are 10 x 10.
I am expecting Z to be zeros matrix of 10x10. But I am getting Z to be a 0 of 1x1.
Why?
채택된 답변
추가 답변 (2개)
h = @(x,y) zeros(10)
[X, Y] = meshgrid(linspace(0, 2, 10));
Z = h(X,Y)
댓글 수: 11
Nilay Modi
2024년 3월 29일
Replace 10 by size(x):
h = @(x,y) zeros(size(x));
[X, Y] = meshgrid(linspace(0, 2, 10));
Z = h(X,Y)
Nilay Modi
2024년 3월 29일
Then you will have to pass this information as input to the function handle.
You could do
h = @(x,y) zeros(size(x))
or more general
h = @(x,y,m,n) zeros(m,n);
[X, Y] = meshgrid(linspace(0, 2, 10));
Z = h(X,Y,10,10)
Nilay Modi
2024년 3월 29일
And what would you expect MATLAB to return if x and y have different sizes ? Should it read your mind ?
You must explicitly tell MATLAB the size of the matrix of zeros it should return. In your case
h = @(x,y) 0
you told MATLAB to return the scalar 0 - independent of the sizes of the inputs.
Bruno Luong
2024년 3월 29일
편집: Bruno Luong
2024년 3월 29일
Believe or not MATLAB is not yet smater than you. It does exacly what you tell it to do (returning scalar 0)
Nilay Modi
2024년 3월 29일
Nilay Modi
2024년 3월 29일
Torsten
2024년 3월 29일
Define
g = @(x,y,m,n) zeros(m,n)
in the script part
and use it as
Z = g(X,Y,size(X,1),size(X,2))
in your function.
Don't overcomplicate things - your code looks complicated enough.
Nilay Modi
2024년 3월 29일
I am expecting Z to be zeros matrix of 10x10. But I am getting Z to be a 0 of 1x1.
Why?
Because that's what you told your function to return.
Based on your later comment, you don't want your function to return a 1-by-1 or even a fixed 10-by-10. You want it to return a zeros matrix the same size as the input. Correct?
f = @(X, Y) zeros(size(X));
X = ones(4)
f(X, X)
Y = ones(5, 8)
f(Y, Y)
Z = 42
f(Z, Z)
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
