# Using vector to access multidimensional array or passing vector as multiple inputs

조회 수: 3 (최근 30일)
Matt Tejer 2022년 6월 17일
답변: Chetan 2024년 1월 5일
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)
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일
It's an output from another function, and it is used in different places, where I do math operations, which don't work for cells ("Operator '-'/'+'/'*' is not supported for operands of type 'cell'.").
But I can duplicate output, one as vector, one as cell. Thanks for sugestion.

댓글을 달려면 로그인하십시오.

### 답변 (1개)

Chetan 2024년 1월 5일
I understand you're looking to access elements in a multidimensional array for MEX file creation without using `num2cell` or `mat2cell`. Your current method of converting subscript indices to a linear index is correct and efficient for this purpose.
Here's a concise way to calculate the linear index:
n = 2;
arraySizes = [n*ones(1,2), 3*ones(1,3)];
A = ones(arraySizes);
ind = [3, 2, 1, 1, 2];
% Calculate cumulative product of array sizes
cumprodSizes = [1, cumprod(arraySizes(1:end-1))];
% Compute linear index and access the element
linearIndex = sum((ind - 1) .* cumprodSizes) + 1;
elementValue = A(linearIndex);
This code calculates the linear index by considering the array's dimensions and then accesses the element directly. It's a MEX-friendly approach and scales with different array dimensions.
Make sure the subscript indices in `ind` are valid for the array's size before indexing.
Hope it helps
Best regards,
Chetan Verma

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by