There are some functions that support variable number of output variables. For example, ind2sub(), depending on the matrix size, could have variable number of output.
if I type:
[I1,I2]=ind2sub([3,4],10);
I get the correct answer, I1=1 and I2=4;
but if I issue:
subIndices=ind2sub([3,4],10);
then I won't get subIndices= [1,4]; but I get subIndices=10; which definitely is not what I wanted.
Now here is my quesitons. What if I don't know the input size and that is defined during the runtime, meaning that my input size once might be [3,4] and another time it would be [3,4,5]. So once I need to call [I1,I2]=ind2sub([3,4],10) but another time I need to have [I1,I2,I3]=ind2sub([3,4,5],10) in the code.
In this easy case I just rewrote another version of ind2sub which outputs the indices as vector, you can see the code at the end of this post; but what is a better way of doing this?
Here is the modified version of ind2sub():
function subIndices = myInd2Sub(inputSize,index)%%myInd2Sub is similar to MATLAB's ind2sub except that the output, i.e.
% the indices for each dimensions, are provided in a single array, instead
% of separate output variables.
% Checking input arguments
validateattributes(inputSize, ... {'numeric'}, ... {'vector','integer','positive'}); validateattributes(index, ... {'numeric'}, ... {'scalar','integer','positive','<=',prod(inputSize)}); % preparing the output
subIndices = zeros(numel(inputSize),1); % changing the index to zero-base
index = index - 1; % calculating the indices for each dimension
for i=numel(subIndices):-1:2 nElem = prod(inputSize(1:i-1)); subIndices(i) = floor(index/nElem); index = index - subIndices(i)*nElem; end subIndices(1) = index; % changing back the indices to 1-base.
subIndices = subIndices + 1; end
Best Answer