Search code examples
matlabmultidimensional-arrayflat-file

MATLAB: Transform a flat file list into a multi-dimensional array


I am completely stuck with this: I start out with a flat file type of list I get from an SQL statement like this and want to transform it into a 4D array.

SELECT a1, a2, a3, a4, v FROM table A;

a1 a2 a3 a4 v
--------------
2 2 3 3 100
2 1 2 2 200
3 3 3 3 300 
...
  • a1 to a4 are some identifiers (integers) from a range of (1:5), which are also the coordinates for the new to be populated 4D array.
  • v is a value (double) e.g. a result from a measurement.

What I now want is to transform this list into a 4D array of dimension (5,5,5,5) where each v is put at the right coordinates.

This could easily be done using a for loop, however as I have lots of data this is not really feasible.

If I had just 1 dimension, I would do somesthing like this:

a1 = [2;5;7];           % Identifiers
v = [17;18;19];         % Values
b1 = (1:10)';           % Range of Identifiers
V = zeros(10,1);        % Create result vector with correct dimensions
idx = ismember(b1, a1); % Do the look up
V(idx) = v;             % Insert

My question: How can I do this for the above mentioned 4D array without using a for loop. Is there a "Matlab Way" of doing it?

Any help is greatly appreciated!

Thanks, Janosch


Solution

  • You should be able to do what you want using linear indexing, and the sub2ind function. It would look something like this.

    x=zeros(5,5,5,5); %initialize output vector
    
    i = sub2ind(size(x),a1,a2,a3,a4);
    
    x(i) = v;