转置矩阵/难以理解bsxfun的工作原理 [英] Transposing matrix / Trouble understanding how bsxfun works

查看:106
本文介绍了转置矩阵/难以理解bsxfun的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个奇怪的问题,因为许多人想知道为什么要在拥有.'运算符的情况下使用像bsxfun这样复杂的函数进行转置.

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.

但是,移调对我来说不是问题.我提出了自己的问题,并尝试使用特定功能解决问题,以便我了解该功能的实际工作方式.我尝试使用bsxfun解决一些示例,并成功获得了预期的结果.但是我以为我已经了解了此功能的工作原理,因此在尝试该示例时发生了改变.

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.

我拍摄的示例图像是2D正方形图像,因此我没有尝试访问不可用的索引.

The example image i've taken is a square 2D image, so that i'm not trying to access an index which is unavailable.

这是我的代码:

im = imread('cameraman.tif');
imshow(im);
[rows,cols] = size(im);

imout = bsxfun(@(r,c) im(c,r),(1:rows).',1:cols);

我遇到的错误:

使用bsxfun时出错
输出尺寸无效.

Error using bsxfun
Invalid output dimensions.

测试错误(第9行)
imout = bsxfun(@(r,c)im(c,r),(1:行).',1:cols);

Error in test (line 9)
imout = bsxfun(@(r,c) im(c,r),(1:rows).',1:cols);

PS:我尝试在im( , )内交换rc(例如:bsxfun(@(r,c) im(r,c),(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.

这是我的循环代码:

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.

推荐答案

这里的问题是您的函数不会返回与给定输入形状相同的输出.尽管对bsxfun的要求是该函数按元素进行操作,但不使用标量元素进行调用.因此,您需要执行以下操作:

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)

这篇关于转置矩阵/难以理解bsxfun的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆