2

Lets say we have an Array A = ones(2, 2, 2) and another matrix P = rand(4). I am wondering if it is possible to write the code

temp = A(:, :, 1);
X = P * temp(:);

into one line of code to save the memory consumed by temp. I tried to run

X = P * A(:, :, 1)(:);

but that does not work. I also fumbled around with the reshape command but could not make it work.

I could not find the answer using the web or this forum. Is it possible to do what I am looking for?

Thank you for the help,

Adrian

Divakar
  • 218,885
  • 19
  • 262
  • 358
awaelchli
  • 796
  • 7
  • 23

2 Answers2

3

You could do -

[m,n,r] = size(A);
X = P*reshape(A(:,:,1),m*n,[])

If you are doing it iteratively along the third dimension of A, i.e. for A(:, :, iter), where iter is the iterator, you could get all X's in a vectorized manner in an array like so -

X_all = P*reshape(A,m*n,[])
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Oh, that could work. I am actually doing it iteratively, so then I could even eliminate the for loop! – awaelchli Jun 04 '15 at 19:14
  • Yeah, that was basically my assumption there! – Divakar Jun 04 '15 at 19:14
  • I just tried it and it works! Thanks a lot. This is the second time you helped me with a reshape problem! You are the reshape-master of matlab!! – awaelchli Jun 04 '15 at 19:22
  • 1
    @aeduG Well I don't remember helping you before, but I do like `reshape`. In other words, I do remember `reshape` ;) – Divakar Jun 04 '15 at 19:23
1

Reshape should work. Try doing it like this:

X = P * reshape(A(:, :, 1), [], 1)
Rafael Monteiro
  • 4,509
  • 1
  • 16
  • 28
  • Thanks for the help, this would have helped me too. I would also select your answer as correct if I could select more than one. Thanks – awaelchli Jun 04 '15 at 19:26