Using vector to access multidimensional array or passing vector as multiple inputs
显示 更早的评论
Hello,
I would like to access multidimensional array using vector like:
n=2
arraySizes=[n*ones(1,2),3*ones(1,3)]
A=ones(arraySizes)
ind=[3,2,1,1,2]
A(ind) % I would like it, if output was a scalar.
or to convert that vector of indices to linear indice:
indN= sub2ind(arraySizes,ind)
A(indN)
I know that it is possible to use cell and {:}, but num2cell and mat2cell aren't supported in MEX creation, so it's also not a solution I look for (and for loop copying num array to cell is very slow).
indCell=num2cell(ind)
indN= sub2ind(arraySizes,indCell{:})
A(indN)
I don't want just use hard indexing, because n isn't constant, and switch case with hundreds hard coded options doesn't seem optimal (but maybe it would be the fastest method then I will).
A(ind(1),ind(2),ind(3),ind(4),ind(5))
My current solution is showed below, but I`m looking for faster approch.
indNum=(ind-ones(1,length(arraySizes)))*((cumprod(arraySizes))./arraySizes).'+1
A(indNum)
Thank you for your time,
Matt
2 个评论
Rik
2022-6-17
How is ind created? It might be easier to make sure it is a cell from the start. Then you can use A(ind{:}).
Matt Tejer
2022-6-17
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!