Finding the address of an element in a multi-dimensional array

3 views (last 30 days)
function [cMatrix] = makeC (n,f)
%n is the degree of the polynomial, f is the number of factors (dimensionality)
A = [];
if f == 1
cMatrix = 2*rand(n+1,1)-1;
else
for i = 1:f
A(1,i) = n+1;
end
cMatrix = rand(A);
end
for i = 1:numel(cMatrix)
coords = ind2sub(size(cMatrix),i);
coordSum = 0;
for ii = 1:numel(coords)
check = check + coords(ii);
if coordSum < f(n+1) - n
cMatrix(i) = 0;
end
end
end
The problem is that ind2sub (a built-in matlab function that converts a linear index into subscripts) does not produce the correct number of coordinates on its own. I have to say something like:
[x , y] = ind2sub([2,2],3)
to make [x,y] become [1 , 2]
but the number of dimensions in the multidimensional array is at the discretion of the user. So I need the output of ind2sub to be a 1xf matrix where f is the number of dimensions named coords. Currently coords is just the linear address! I am new to matlab (like as of yesterday) so please be thorough.
Possibly irrelevant information regarding the purpose of the function: generates a matrix of random coefficients for an nth order polynomial. The problem is that if you want a 2nd order polynomial with 2 factors (3x3 matrix) you don't want terms like x^2*y^2 because that is a quartic term. So the coef matrix for 2nd order 2 factors would look like:
x^2 x c
y^2 0 0 rand#
y 0 rand# rand#
c rand# rand# rand#
The first half of the code makes the appropriately sized matrix the second half iterates through and finds where the zeros go.

Accepted Answer

Stephen23
Stephen23 on 17 Jun 2015
Edited: Stephen23 on 17 Jun 2015
It is easy to create a function that will return the subscript indices in a vector:
function vec = ind2vec(siz,ndx)
tmp = [1,cumprod(double(siz(1:end-1)))];
for k = numel(siz):-1:1,
nxt = 1 + rem(ndx-1, tmp(k));
vec(k) = 1 + (ndx - nxt)/tmp(k);
ndx = nxt;
end
end
And demonstrated:
>> ind2vec([2,2],3)
ans =
1 2
>> ind2vec([2,2,3,4],3)
ans =
1 2 1 1
>> ind2vec([2,2,3,4],32)
ans =
2 2 2 3

More Answers (1)

Guillaume
Guillaume on 17 Jun 2015
I've not tried to understand your code but the technique to solve your problem with ind2sub or similar functions that return varying numbers of outputs (or take varying numbers of inputs) is to use the expansion of cell arrays into comma separated list. For example:
numberofdimensions = 5;
coords = cell(1, numberofdimensions);
[coords{:}] = ind2sub(size(somematrix), someindex);
coords = cell2mat(coords);

Categories

Find more on Statistics and Machine Learning Toolbox 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!