Peter Blomgren
San Diego State University
SDSU Logo
Matlab Learning Resources Status — Abandoned
main  |  code  |  video  ||  home
 
access
%
% Accessing vector and matrix elements
%


% Set the size of the matrix and vecor in this example
rows = 5;
cols = 5;

% Generate a matrix, and vector filled with zeros.
A = zeros(rows,cols);
x = zeros(rows,1);

% Generate a Hilbert matrix, just for fun
for r = 1:rows
  for c = 1:cols
    A(r,c) = 1/(1+r+c);
  end
end

% Simple output with "disp" command (just give the variable name)
A

% Let x be a vector of Fibonacci numbers
x(1) = 1;
x(2) = 1;
for k = 3:cols
  x(k) = x(k-1) + x(k-2);
end

% Formatted output with sprintf/fprintf command
disp(['x = [' sprintf(' %d ',x) ']'''])

% Common Matrix-vector operations
v = A*x;  % Matrix-vector product
w = A\x;  % Here, w is the solution to A*w = x

% Output of results
disp(['v = [' sprintf(' % 10.4g ',v) ']'''])
disp(['w = [' sprintf(' % 10.4g ',w) ']'''])
A =
    0.3333    0.2500    0.2000    0.1667    0.1429
    0.2500    0.2000    0.1667    0.1429    0.1250
    0.2000    0.1667    0.1429    0.1250    0.1111
    0.1667    0.1429    0.1250    0.1111    0.1000
    0.1429    0.1250    0.1111    0.1000    0.0909
x = [ 1  1  2  3  5 ]'
v = [      2.198       1.837       1.583       1.393       1.245 ]'
w = [  4.169e+04  -3.875e+05   1.163e+06  -1.399e+06   5.844e+05 ]'
Copyright © 2024 Peter Blomgren.