>> % Matlab can be used as a calculator. >> 1+2*3 ans = 7 >> ans/4 ans = 1.7500 >> % Matlab can store vectors (column vectors or row vectors). >> v = [1; 2; 3; 4] v = 1 2 3 4 >> w = [5, 6, 7, 8] w = 5 6 7 8 >> % You can refer to an entry of a vector by giving its index. >> v(2) ans = 2 >> w(3) ans = 7 >> % You can add two vectors of the same dimensions, but you cannot >> % add v and w because v is 4X1 and w is 1X4. If you try, Matlab >> % will give you an error message. >> v+w ??? Error using ==> + Matrix dimensions must agree. >> % w' is the transpose of w. >> w' ans = 5 6 7 8 >> % We can add v and w' using ordinary vector addition. >> v + w' ans = 6 8 10 12 >> % The following computes the sum of the entries of v. >> v(1) + v(2) + v(3) + v(4) ans = 10 >> % So does the following "for" loop. >> sumv = 0; >> for i=1:4, sumv = sumv + v(i); end; >> sumv sumv = 10 >> % Here we set a random vector of length n=100. >> n = 100; >> v_rand = randn(n,1); >> % Now we really need a "for" loop to sum the entries of v_rand. >> sumv_rand = 0; >> for i=1:n, sumv_rand = sumv_rand + v_rand(i); end; >> sumv_rand sumv_rand = 4.7929 >> % Actually, Matlab has a built-in function called "sum" to add >> % the entries of a vector. To find out about it, type "help sum". >> help sum SUM Sum of elements. For vectors, SUM(X) is the sum of the elements of X. For matrices, SUM(X) is a row vector with the sum over each column. For N-D arrays, SUM(X) operates along the first non-singleton dimension. SUM(X,DIM) sums along the dimension DIM. Example: If X = [0 1 2 3 4 5] then sum(X,1) is [3 5 7] and sum(X,2) is [ 3 12]; See also PROD, CUMSUM, DIFF. >> sum(v_rand) ans = 4.7929 >> % Matlab can also store matrices. >> A = [1, 2, 3; 4, 5, 6; 7, 8, 0] A = 1 2 3 4 5 6 7 8 0 >> b = [0; 1; 2] b = 0 1 2 >> % Matlab has lots of built-in functions for solving matrix >> % problems. For example, to solve the linear system Ax=b, >> % type "A\b". >> x = A\b x = 0.6667 -0.3333 0.0000 >> % We can check this answer by computing b - A*x. Note that >> % when we type A*x, this means the usual matrix-vector multiplication, >> % and when we subtract the result from b, this is a vector >> % subtraction. This should give a vector of 0's, if x solves >> % the system exactly. Since our machine carries only about >> % 16 decimal places, we do not expect it to be exactly zero, >> % but, as we will see later, it should be of size about 1.e-16. >> b - A*x ans = 1.0e-15 * -0.0740 -0.2220 0 >> % Not bad! >> exit