Answer to Question #52515 in MatLAB | Mathematica | MathCAD | Maple for jason

Question #52515
Now, for each of the for-loop examples on the next page, write two programs that generate the same arrays (1-D, 2-D and 3-D), with the following changes: 1. Modify the programs to pre-allocate the arrays first 2. Use vectorisation functions to implement the programs without the use of any loops. You may want to look at ndgrid, and remember to use array versions of your operators! % 1-D array (3 * i) n = 10; for i=1:n A(i) = 3*i; end % 2-D array where % B(i,j) = i/j n = 10; for i=1:n for j=1:n B(i,j) = i/j; end end % 3-D array where % C(i,j,k) = i*j+k n = 10; for i=1:n for j=1:n for k=1:n C(i,j,k) = i*j+k; end end end
1
Expert's answer
2015-06-04T03:39:51-0400
Now, foreach of the for-loop examples on the next page, write two programs that
generate the same arrays (1-D, 2-D and 3-D), with the following changes:
1. Modify the programs to pre-allocate the arrays first
2. Use vectorisation functions to implement the programs without the use of any
loops. You may want to look at ndgrid, and remember to use array versions of
your operators!
% 1-D array(3 * i)
n = 10;
for i=1:n
A(i) = 3*i;
end

% 2-D array where
% B(i,j) = i/j
n = 10;
for i=1:n
for j=1:n
B(i,j) = i/j;
end
end

% 3-D array where
% C(i,j,k) = i*j+k
n = 10;
for i=1:n
for j=1:n
for k=1:n
C(i,j,k) = i*j+k;
end
end
end

Solve
Pre-allocate vector by set 0 to all elements byfunction zeros(n,n,n).
 
 
% 1-D array (3 * i)
n = 10;
A=zeros(n,1);%pre-allocate arrays
I=zeros(n,1);
I=linspace(1,n,n);
A=I.*3;
% 2-D array where
% B(i,j) = i/j
n = 10;
B=zeros(n,n);
I_1=1./I;
B=I'*I_1;
 
% 3-D array where
% C(i,j,k) = i*j+k
n = 10;
C=zeros(n,n,n);
[X,Y,Z]=ndgrid(I,I,I_1);
C=X.*Y+Z;
%C(i,j,k) = i*j+k;

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS
paypal