Search code examples
imagematlabmatrixtransposebsxfun

Transposing matrix / Trouble understanding how bsxfun works


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.


Solution

  • 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:

    x = randi(5, 4, 5)
    [m, n] = size(x);
    bsxfun(@(r, c) transpose(x(c, r)), (1:n)', 1:m)