bsxfun implementation in matrix multiplication

前端 未结 5 564
孤城傲影
孤城傲影 2020-11-28 14:36

As always trying to learn more from you, I was hoping I could receive some help with the following code.

I need to accomplish the following:

1) I have a vect

5条回答
  •  感情败类
    2020-11-28 15:13

    Just to add an alternative, you maybe can use cellfun to achieve what you want. Here's an example (slightly modified from yours):

    x = randi(2, 5, 3)-1;
    a = randi(3,3);
    %// bsxfun 3D (As implemented in the accepted solution)
    val = bsxfun(@and, a, permute(x', [3 1 2])); %//'
    out = reshape(permute(val,[1 3 2]),size(val,1)*size(val,3),[]);
    %// cellfun (My solution)
    val2 = cellfun(@(z) bsxfun(@and, a, z), num2cell(x, 2), 'UniformOutput', false);
    out2 = cell2mat(val2); % or use cat(3, val2{:}) to get a 3D matrix equivalent to val and then permute/reshape like for out
    %// compare
    disp(nnz(out ~= out2));
    

    Both give the same exact result.

    For more infos and tricks using cellfun, see: http://matlabgeeks.com/tips-tutorials/computation-using-cellfun/

    And also this: https://stackoverflow.com/a/1746422/1121352

提交回复
热议问题