This could be a weird question because Many would be wondering why to use such a complicated function like bsxfun
for transposing while you have the .'
operator.
But, transposing isn't a problem for me. I frame my own questions and try to solve using specific functions so that i learn how the function actually works. I tried solving some examples using bsxfun
and have succeeded in getting desired results. But my thought, that i have understood how this function works, changed when i tried this example.
The example image i've taken is a square 2D image, so that i'm not trying to access an index which is unavailable.
Here is my code:
im = imread('cameraman.tif');
imshow(im);
[rows,cols] = size(im);
imout = bsxfun(@(r,c) im(c,r),(1:rows).',1:cols);
Error i got:
Error using bsxfun
Invalid output dimensions.Error in test (line 9)
imout = bsxfun(@(r,c) im(c,r),(1:rows).',1:cols);
PS: I tried interchanging r
and c
inside im( , )
(like this: bsxfun(@(r,c) im(r,c),(1:rows).',1:cols)
) which didn't pose any error and i got the same exact image as the input.
I also tried this using loops and simple transpose using .'
operator which works perfectly.
Here is my loopy code:
imout(size(im)) = 0;
for i = 1:rows
for j = 1:cols
imout(i,j) = im(j,i);
end
end
Answer i'm expecting is, what is wrong with my code, what does the error signify and how could the code be modified to make it work.
The problem here is that your function doesn't return an output the same shape as the input it is given. Although the requirement for
bsxfun
is that the function operates element-wise, it is not called with scalar elements. So, you need to do this:You can use the
anonymous function
withbsxfun
like so -I wanted to know how
bsxfun
works so i created a function like this:bsxfun
test function:My script:
Output: (not the value of output of the function. These are those which are printed within
bsxfuntest.m
function usingdisp
)Conclusion:
Try this:
Try this:
Try this:
and this:
Coming to the problem
Taking the code in the question:
When i try
im(c,r)
i.eim(1,(1:5).')
Here,
bsxfun
expects a column vector while the output is a row vector. I guess that is the reason why MatLab produces an error statingThis was also the reason why i didn't get any error when i replaced
r
andc
in the above code like thisbsxfun(@(r,c) im(r,c),(1:rows).',1:cols)
. Because here, the output was a column vector itself.So i tried to transpose the results to obtain the column vector like this:
The code is exactly the same as Edrics's solution and it gives the expected results.