MATLAB is an abbreviation for "matrix laboratory." All MATLAB variables are multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used for linear algebra. a = [1 2 3; 4 5 6; 7 8 10] a = 1 2 3 4 5 6 7 8 10 Without semicolon, display the data items. Another way to create a matrix is to use a function, such as ones, zeros, or rand. For example, create a 5-by-1 column vector of zeros. z = zeros(5,1) z = 0 0 0 0 0 format long To perform element-wise multiplication rather than matrix multiplication, use the .* operator: p = a.*a The matrix operators for multiplication, division, and power each have a corresponding array operator that operates element-wise. a.^3 Array indexing a(2, :) ans = 4 5 6 a(2, 3) ans = 6 a(2) a(1:3,2) myText = 'Hello, world'; disp('hello world'); clc The clc function clears the Command Window. x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x') ylabel('sin(x)') title('Plot of the Sine Function')
To add plots to an existing figure, use hold. %x = 0:pi/100:2*pi; x = linspace(0, 2*pi, 100); y = sin(x); plot(x,y, 'b--o'); hold on y2 = cos(x); plot(x,y2,'r^') legend('sin','cos') grid; xlabel('x') ylabel('sin(x) and cos(x)') title('Plot of the sin and cos functions');
% Means comments in Matlab programs % meshgrid function generates x and y coordinates for a 2D grid [X,Y] = meshgrid(-2:.2:2); Z = X .* exp(-X.^2 - Y.^2); surf(X,Y,Z)
% subplot function divides a figure into multiple areas so multiple plots appear on the same figure. t = 0:pi/10:2*pi; [X,Y,Z] = cylinder(4*cos(t)); subplot(2,2,1); mesh(X); title('X'); subplot(2,2,2); mesh(Y); title('Y'); subplot(2,2,3); mesh(Z); title('Z'); subplot(2,2,4); mesh(X,Y,Z); title('X,Y,Z');
© Copyright Texas Wesleyan University. All Rights Reserved.