2

I'd like to create an array from elements in an 3D-matrix using z-coordinates stored in an another array. The simplest way would be:

X=2;
Y=3;
lastZ=10000000
for i=1:lastZ
    new_array=matrix(X,Y,Z(i));
end

But I'm looking for a "vectorized" way using only matrices instead of for-loop. I've tried the following code but I get an error message "Subscript indices must either be real positive integers or logicals":

new_array=matrix(X,Y,Z);

I understand that Z is an array and cannot be put with X and Y which are integers. Is there a better way to create such array in one-liner code?

1 Answer 1

3

You can try:

new_array=squeeze(matrix(X,Y,1:Z));
Sign up to request clarification or add additional context in comments.

4 Comments

That's clear and clean! I've spent hours trying to understand bsxfun and arrayfun but squeeze... But I still wonder why new_array=matrix(X,Y,Z) doesn't work while the only difference in your code is the usage of squeeze to flatten the new_array? I mean is there a problem in my indexing.
If you index any dimension beyond the second, you do not get a "normal" vector. Look at it yourself by displaying matrix(X,Y,1:10). Actually, I had lots of trouble too before I stumbled upon squeeze.
Apparently, using squeeze is much slower than a straight for loop !!! I'm on Matlab 2012a. I've read a lot about the improvement in for loops performance . It appears like my code gets worse in term of running time with every vectorization step. Maybe because of functions like find, sum or squeeze as I want to avoid any for loops.
On my system with Matlab 2009a, the squeeze version takes about a third of the time the loop version takes.

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.