Ansh
Ansh

Reputation: 89

Making a 3d array MATLAB

In MATLAB I have

[Z,S]=meshgrid(0.01:0.01:1)

and I also have a 100000x2 matrix called X, each row has two sets of data - p is the first column and x is the 2nd.

I want to compute exp^(-S*X(j,2)).(*Z.^X(j,1)) where j indexes the row. The result should be a 100x100x100000 matrix. This will then be averaged along the 3rd dimension and a mesh plot will be produced. I've tried using a for loop

[Z,S]=meshgrid(0.01:0.01:1)
for j=1:100000
phi(j)=exp^(-S.*X(j,2)).*(Z.^X(j,1))
end

to produce the 100x100x100000 array I need. However this gives me the error

In an assignment  A(I) = B, the number of elements in B and I must be the same.
Error in phi (line 4)
phi(j)=exp(-S.*X(j,2)).*(Z.^X(j,1));

I'm not sure why this is happening? Can anyone figure out a better way of trying to find the result I want? Because I'm guessing there could be a fully vectorised solution (or least use of for loops)?

Upvotes: 1

Views: 101

Answers (1)

Divakar
Divakar

Reputation: 221684

Assume that you are using two more nested loops to get Z and S, thus the code would have three nested loops in total.

Now, the vectorizing techniques haven't changed on vectorizable nested loops cases like these - Treat different parts of the code that involve different iterators separately. Thus, here you have three iterators, two of which are 100 in length and the third ones goes until 100000. Putting the vectorizing ideas in a concise commented text and solving your case with bsxfun based code -

%// Get vectorized equivalent of exp(-S.*X(j,2)) and keeping in mind that
%// since the last (3rd) dimension of final output has length same as the 
%// number of elements in X(:,2), so "throw" this to 3rd dim with permute. 
%// Then, use bsxfun to let the broadcasting being taken care off by MATLAB.
p1 = exp(-bsxfun(@times,V.',permute(X(:,2),[3 2 1]))); %//'

%// Going with same philosophy as before, get vectorized (Z.^X(j,1))
p2 = bsxfun(@power,V,permute(X(:,1),[3 2 1]));

%// Finally "merge" earlier two parts for final output
phi_out = bsxfun(@times,p1,p2);

Upvotes: 2

Related Questions