filling matrix instead of using for loops

Hi,
I want to fill my Matrix in following way.
I have 2 vectors that are used by my Matrix. Say
VectorA = 1:10;
VectorB = 20:29;
And I want to use them to fill my matrix.
for m = 1:10
for n = 20:29
MatrixK = [sin(m),cos(n);cos(n).*sin(m),exp(m)];
% MatrixK will be used here
end
end
However, as you know, it is not efficient as these 2 for loops have to be run by 100x100 times. How can I do it efficiently? I am not sure I have fully defined my problem. Most likely, I will add sth.
Thanks

 Accepted Answer

A = 1:10;
B = 20:29;
[m,n] = ndgrid(A,B)
K = [sin(m),cos(n);cos(n).*sin(m),exp(m)];
s = size(K);
p = size(m);
q = s./p;
z0 = reshape(K,p(1),p(2),q(1),q(2));
MatrixK = reshape(permute(z0,[2 1 4 3]),s(1),[]);

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 26 Jun 2014

Edited:

on 26 Jun 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!