0

I have been trying to use the multidimensional array function to store NxN vectors of length n in each (i,j) entry of a 3d matrix of NxNxn dimensions. My code looks like:

    a=zeros(N,N,n);
    a(i,j,:)=v_ij; %here v is a vector of length n, which differs for each i,j

However when I try to extract each vector by typing e.g. a(1,1,:) I don't get a nice vector. Rather I get something like:

    ans(:,:,1) = ..
    ans(:,:,2) = ..
    ...

I don't understand why it says ans(:,:)...

1
  • It's because a(1,1,:) is a vector along the third dimension of the matrix. See if squeeze(a(1,1,:)) is what you want Commented Nov 20, 2015 at 18:30

2 Answers 2

2

That's because each vector v_ij is stored along the 3rd dimension of your matrix, so when you access a(1,1,:), you are looking for a multidimensional array consisting of every value at the location (1,1) along the 3rd dimension of a.

Let's consider a simple example:

N = 2;
n = 3;

a = zeros(N,N,n);

for k = 1:N

    for l = 1:N

        v_kl = randi([0 10],1,n);
        a(k,l,:) = v_kl;

    end
end

The randomly-generated matrix a is a 2x2x3 matrix that looks like this:

a(:,:,1) =

     4     1
     4    10


a(:,:,2) =

     0     2
     0     5


a(:,:,3) =

     2     2
     9     5

Therefore, using a(1,1,:) is equivalent to getting the element located at (1,1) for all 3 dimensions, here it would be 4,0 and 2.

Indeed, calling a(1,1,:) yields:

ans(:,:,1) =

     4


ans(:,:,2) =

     0


ans(:,:,3) =

     2
Sign up to request clarification or add additional context in comments.

Comments

0

Benoit_11's answer plus squeeze should work, but I would like to propose a different solution.

Rather than creating a NxNxn array, why not make it nxNxN?

N = 2;
n = 3;

a = zeros(n,N,N);

for p = 1:N
    for q = 1:N
        v_pq = randi([0 10],1,n);
        a(:,p,q) = v_pq;
        if (p == 1) && (q == 1)
           v_pq   %// display vector at a(:,1,1)
        end
    end
end

a


v_pq =

   3   4   8

a =

ans(:,:,1) =

   3   3
   4   9
   8   7
ans(:,:,2) =

    5    6
   10    1
    9    5

Now the vectors are stored along the first dimension, so [3 4 8] shows up as the first column of ans(:,:,1). To access it you would use a(:,p,q) rather than a(p,q,:):

a(:,1,1)

ans =

   3
   4
   8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.