Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Matrix assembler Write a MATLAB function M-file named makemat to receive three r

ID: 3552038 • Letter: M

Question

Matrix assembler

Write a MATLAB function M-file named makemat to receive three row arrays as input, and from them, create and return a matrix with three rows as output.

Example:

>> a=[1:3];b=[4:6];c=[7:9]; >> M = makemat(a,b,c)
M=

123

456

789

You may not assume that the row arrays are the same size. You will pad the shorter arrays with zeroes to make up the difference.

The shortest array(s) should be right-justified (padded with zeroes on the left)

The middle sized array should be left-justified (padded with zeroes on the right)

The longest array should have no padding

Examples:

>> a=[1:5];b=[9:-1:7];c=[6]; >> makemat(a,b,c)
ans =

12345

98700

00006

>> makemat(c,b,c) ans =

006

987

006

Explanation / Answer

function D = makemat(A,B,C)

max_size = 0;

min_size = 100000; %A very Large number

size_A = size(A);

size_B = size(B);

size_C = size(C);

  

if(max_size<size_A(2))

max_size = size_A(2);

max_i=1;

max = A;

end

if(max_size<size_B(2))

max_size = size_B(2);

max_i=2;

max = B;

end

if(max_size<size_C(2))

max_size = size_C(2);

max_i=3;

max = C;

end

if(min_size>size_A(2))

min_size = size_A(2);

min_i=1;

min = A;

end

if(min_size>size_B(2))

min_size = size_B(2);

min_i=2;

min = B;

end

if(min_size>size_C(2))

min_size = size_C(2);

min_i=3;

min = C;

end

remaining_row = 6 - min_i - max_i; %To find the middle sized row

if(remaining_row==1)

rem = A;

end

if(remaining_row==2)

rem = B;

end

if(remaining_row==3)

rem = C;

end


size_temp = size(rem); %Size of middle size row

remaining_row_size = size_temp(2);

D(min_i,:) = padarray(min,[0,max_size - min_size],0,'pre'); %The shortest array(s) should be right-justified

D(max_i,:) = max; %The longest array should have no padding

D(remaining_row,:) = padarray( rem,[0,remaining_row_size - min_size],0,'post'); %The middle sized - left-justified

end