01.09.2014 Views

Programming with SCILAB (pdf)

Programming with SCILAB (pdf)

Programming with SCILAB (pdf)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

or,<br />

--> surf(x,y,z’)<br />

9.7<br />

0.0<br />

-9.7<br />

-2.50<br />

0.00<br />

2.50 10<br />

5<br />

0<br />

Nested loops can be used for other operations <strong>with</strong> matrices. For example, a function<br />

that multiplies two matrices is shown next:<br />

function [C] = matrixmult(A,B)<br />

//|--------------------------------------|<br />

//| This function calculates the matrix |<br />

//| C(nxm) = A(nxp)*B(pxm) |<br />

//|--------------------------------------|<br />

//First, check matrices compatibility<br />

[nrA,ncA] = size(A)<br />

[nrB,ncB] = size(B)<br />

if ncA nrB then<br />

error('matrixmult - incompatible matrices A and B')<br />

abort<br />

end<br />

//Calculate matrix product<br />

C = zeros(nrA,ncB)<br />

for i = 1:nrA<br />

for j = 1:ncB<br />

for k = 1:ncA<br />

C(i,j) = C(i,j) + A(i,k)*B(k,j)<br />

end<br />

end<br />

end<br />

An application of function matrixmult is shown next. Here we multiply A 3x4 <strong>with</strong> B 4x6<br />

resulting in C 3x6 . However, the product B 4x6 times A 3x4 does not work.<br />

-->A = int(10*rand(3,4))<br />

A =<br />

! 2. 3. 8. 0. !<br />

! 7. 6. 6. 5. !<br />

! 0. 6. 8. 6. !<br />

-->B = int(10*rand(4,6))<br />

B =<br />

! 7. 2. 3. 3. 3. 2. !<br />

! 1. 2. 9. 2. 5. 6. !<br />

! 5. 8. 2. 5. 5. 4. !<br />

! 2. 6. 3. 4. 4. 9. !<br />

-->C = matrixmult(A,B)<br />

19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!