Extract unknown number of vectors from matrix
1 次查看(过去 30 天)
显示 更早的评论
Hey there,
I want to use the function sub2ind on the column vectors of a matrix M, let's say of size . The function sub2ind asks for: ind = sub2ind(sz,I1,I2,...,In), i.e. I would need n vectors of size as input. If I'd know the (small) number of vectors, of course I could go for I1 = M(:,1), I2 = M(:,2), ...
The problem: it doesn't run on the matrix M directly and I don't know the number of columns n beforehand. num2cell would create separated cells with the n vectors of size , but sub2ind also does not run on cells.
I couldn't find a solution for the problem; how do I get efficiently n separate vectors from a matrix with unknown size n? Is that possible? If not, how can I solve the described problem with sub2ind?
Thanks a lot for your help!
0 个评论
采纳的回答
Stephen23
2020-10-22
编辑:Stephen23
2020-10-22
" num2cell would create separated cells with the n vectors of size, but sub2ind also does not run on cells."
True, but you can easily use a cell array to create a comma-separated list, e.g.:
spl = num2cell(M,1);
idx = sub2ind(sz,spl{:});
"how do I get efficiently n separate vectors from a matrix with unknown size n? Is that possible?"
Yes, use num2cell to create a cell array of vectors.
"how can I solve the described problem with sub2ind?"
Use a comma-separated list generated from that cell array.
4 个评论
Stephen23
2020-10-22
编辑:Stephen23
2020-10-22
"No your code isn't doing the right thing"
Really? Did you even try it? It gives exactly the same output as that (badly-named) third party code you linked to. I downloaded that FEX function, renamed it to sub2idx, and compared its output aginst the (very standard MATLAB) code that I gave you in my answer. Lets have a look:
>> M = randi(9,3,5); % 3x5 random indices
>> S = 9*ones(1,5); % size
>> C = num2cell(M,1); % split
>> X = sub2ind(S,C{:})
X =
20421
8960
52607
>> Y = sub2idx(S,M.') % FEX 36458
Y =
20421 8960 52607
So far I am struggling to see why you would write that my "code isn't doing the right thing", given that it returns exactly the same values as what your linked-to FEX code does, just without any third-party functions required.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!