Extract unknown number of vectors from matrix

1 view (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 22 Oct 2020
Edited: Stephen23 on 22 Oct 2020
" 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 Comments
Stephen23
Stephen23 on 22 Oct 2020
Edited: Stephen23 on 22 Oct 2020
"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.
math4
math4 on 22 Oct 2020
Yes, of course I tried, but just quickly and my sincere apologies - I mismatched dimensions, since I had it transposed for the other code. Thanks for your solution, that's great.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!