Evaluation of function handle matrix erases values

I work with a function handle which has a form looking similar to this:
f = @(x,y) [x;0]
When I just evaluate f with for example x = 1 and y = 1, I receive [1;0]. But if I take for example x = [1;1] and y = [1;1] I receive the vector [1;1;0] instead of [1;0;1;0] which I would expect. Why does matlab erase the second zero? I know that there are easy solutions to move around the problem but I work with a big amount of functions where I cant just sort out the ones with zeros at one position of the function handle matrix.
Thanks for your help!

답변 (2개)

Stephen23
Stephen23 2017년 11월 15일
편집: Stephen23 2017년 11월 15일
"I receive the vector [1;1;0] instead of [1;0;1;0] which I would expect"
Your function
f = @(x,y) [x;0]
concatenates zero onto the bottom of x, and returns this. Your function ignores y completely. That output you get is exactly what I would expect. Lets try it:
>> f = @(x,y) [x;0];
>> f([1;2;3],NaN)
ans =
1
2
3
0
>> f(5,99999999999)
ans =
5
0
So it correctly concatenates zero onto the bottom of x and ignores y, which is exactly what you wrote it to do. You do not explain why you expect this code to do something different. In any case, if you do not want to concatenate zero onto the bottom of x, then you need to specify exactly what you want to do and write the code to do it. Currently the code is doing exactly what it would be expect to do by anyone who had read the MATLAB documentation:
"Why does matlab erase the second zero?"
What "second zero"? Where should this "second zero" be? Second to what?

댓글 수: 1

Okey thanks I understand what you mean.
What I want is that matlab treats the zero in the handle as if it were a function of x and y. Like as if I would say:
g = @(x,y) [x,y]
Then for x = [1;1] and y = [2;2] matlab would give out [1;2;1;2].

댓글을 달려면 로그인하십시오.

Andrei Bobrov
Andrei Bobrov 2017년 11월 15일
>> f = @(x,y) reshape([x(:)';zeros(1,numel(x))],[],1);
>> f([1,1],[1,1])
ans =
1
0
1
0
>>

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2017년 11월 15일

편집:

2017년 11월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by