简体   繁体   English

获得八度/ matlab中的索引矩阵

[英]Obtain matrix of indices in octave / matlab

Given some multidimensional matrix A in Octave / Matlab, 给出Octave / Matlab中的一些多维矩阵A,

What's the easiest way to get a matrix of the same size as A where all elements are replaced by their index along the k'th dimension 获得与A相同大小的矩阵的最简单方法是什么,其中所有元素都被它们沿着第k维度的索引替换

ie for the matrix 即对于矩阵

A =

ans(:,:,1) =

   0.095287   0.191905
   0.226278   0.749100

ans(:,:,2) =

   0.076826   0.131639
   0.862747   0.699016

I want a function f such that f(A,1) = 我想要一个函数f,使得f(A,1)=

ans(:,:,1) =

   1   1
   2   2

ans(:,:,2) =

   1   1
   2   2

f(A,2) = f(A,2)=

ans(:,:,1) =

   1   2
   1   2

ans(:,:,2) =

   1   2
   1   2

and

f(A, 3) = f(A,3)=

ans(:,:,1) =

   1   1
   1   1

ans(:,:,2) =

   2   2
   2   2

Also, given a sparse matrix B 另外,给定稀疏矩阵B.

What's the easiest way to get another sparse matrix of the same size where the nonzero elements are replaced by their index along the k'th dimension? 获得另一个相同大小的稀疏矩阵的最简单方法是什么,其中非零元素被其第k维度的索引替换? (so same problem as above, but for only the nonzero elements) (与上述问题相同,但仅限于非零元素)

Ideally I'm looking for a way which is well-vectorized for octave (meaning it doesn't explicitly loop over anything) 理想情况下,我正在寻找一种适合八度音程的方法(意味着它没有明确地循环任何东西)

CLARIFICATION: For the sparse matrix one, I'm looking for a solution which does not involve creating a full size(B) matrix at any point 澄清:对于稀疏矩阵,我正在寻找一种不涉及在任何点创建全尺寸(B)矩阵的解决方案

ndgrid() does what you want, although not in the format you are looking for. ndgrid()做你想要的,虽然不是你想要的格式。 If you know the dims of the input A beforehand, you can use the following line to create the N-dimentional mesh grid: 如果您事先知道输入A的暗淡,则可以使用以下行创建N维网格:

% for matrix a where ndims(a) == 3
[x, y, z] = ndgrid (1:size(a,1), 1:size(a,2), 1:size(a,3));
% x is like f(a, 1)
% y is like f(a, 2)
% z is like f(a, 3)

You may be able to write a custom wrapper around ndgrid() to convert it to the function format you are looking for. 您可以围绕ndgrid()编写自定义包装器,将其转换为您要查找的函数格式。

In case anyone's curious, since I didn't know about ndgrid, here's the answer I came up with: 如果有人好奇,因为我不知道ndgrid,这是我想出的答案:

function [y] = indices(a,k)
    s = size(a);
    n = s(k);
    D = length(s);
    x = permute(a,[k,1:(k-1),(k+1):D]);

    y = reshape(x,n,[]);
    y = diag(1:n) * ones(size(y));
    y = reshape(y,size(x));

    y = permute(y,[(2:k),1,(k+1):D]);
endfunction

function [y] = spindices(a,k)
    s = size(a);
    n = s(k);
    D = length(s);
    x = permute(a,[k,1:(k-1),(k+1):D]);

    y = reshape(x,n,[]);
    y = spdiag(1:n) * spones(y);
    y = reshape(y,size(x));

    y = permute(y,[(2:k),1,(k+1):D]);
endfunction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM