Indexing of unknown dimensional matrix

非 Y 不嫁゛ 提交于 2019-11-27 14:46:26

For the general case where J can be any length (which I assume always matches the number of dimensions in M), there are a couple options you have:

  1. You can place each entry of J in a cell of a cell array using the num2cell function, then create a comma-separated list from this cell array using the colon operator:

    cellJ = num2cell(J);
    output = M(cellJ{:});
    
  2. You can sidestep the sub2ind function and compute the linear index yourself with a little bit of math:

    sizeM = size(M);
    index = cumprod([1 sizeM(1:end-1)]) * (J(:) - [0; ones(numel(J)-1, 1)]);
    output = M(index);
    

Here is a version of gnovices option 2) which allows to process a whole matrix of subscripts, where each row contains one subscript. E.g for 3 subscripts:

J = [5 2 7 1 
     1 5 2 7
     4 3 9 2];

sizeM = size(M);
idx = cumprod([1 sizeX(1:end-1)])*(J - [zeros(size(J,1),1) ones(size(J,1),size(J,2)-1)]).';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!