L02-Matrices and Arrays
L02-Matrices and Arrays
• When you do not specify an output variable, MATLAB uses the variable ans,
short for answer, to store the results of your calculation.
• >> sin(a)
• ans =
• 0.8415
2D – Array 3D – Array
• >> O = O+10;
• >> sin(a);
• https://in.mathworks.com/help/phased/ref/physconst.html
• >> a = sin(30)
• >> a =sin(pi/6)
• >> a = sqrt(16)
• You can perform calculations within the square brackets.
• x = [abs(-4) 4^2];
• y= [sqrt(10) pi^2]
• X = rand(size(X));
• A(row,col)
• Try : A(1:3,2)
• Try : A(3,:)
• Try : A(2,2:end)
• A(2:4,1:2)
• A(14) = A(2,4)
• A([6 12 15]) = 11 15 12
• Many MATLAB functions that start with is return logical arrays and are
very useful for logical indexing.
• FIND returns a vector containing the linear indices of each nonzero element
in array X.
• k = find(X<10,5) ; Find the first five elements that are less than 10
• X(k) ; View the corresponding elements of X.
• A(1,4)=0.5
• A(1,end)=0.2
Matrix and column vector with the same number of Column vector, Row vector
rows.
• B = cat(3,A,[3 2 1; 0 9 8; 5 3 7])
• The cat function can be a useful tool for building multidimensional
arrays.
• Try : D = A( 2:3, :, : )
• To find the second and third rows of each page, use the colon operator to create
your index vector.
1 3 5 7 5
9 6 7 5 5
8 5 2 9 3
2 4 9 8 2
0 3 3 8 1
1 0 6 4 3
reshape operates columnwise, creating the new matrix by taking consecutive elements down each
column of A, starting with the first page then moving to the second page.
• M(:,:,1) = [1 2 3; 4 5 6; 7 8 9];
• M(:,:,2) = [0 5 4; 2 7 6; 9 3 1];
• >> A = repmat(10,3,2)
• A = 3×2
• 10 10
• 10 10
• 10 10
• Try : B = repmat(A,2,3);
• Example :
• Try : A = [1 2; 3 4];
• T = table(LastName,Age,Employed,Height,Weight,BloodPressure);
1/21/2025 Matrices and Arrays 36
Table Array
• meanHeight = mean(T.Height); - Performing calculations
• Rectangle.L = 10;
• Rectangle.W = 5;
• Rectangle.Area = Rectangle.L * Rectangle.Area
• s = struct(obj) creates a scalar structure with field names and values that
correspond to properties of obj.