This program will multiply 2 m x m matrices and print the results to a file called ‘matrix.txt’EXACTLY as shown in the example output at the bottom of this page (including the horizontal and verticallines). The user should enter a value for m and then input each of the matrix elements as shown in the exampleoutput. Each matrix must be stored as a multidimensional (multiple-scripted) array. Each element in the outputshould be printed to 1 decimal place. Assume all the matrix elements entered by the user are small enough thateach of the elements in the output matrix is less than 100.Note that MatLab can perform matrix multiplication for you, i.e. if you have 2 m x m matrices named A and B,typing A*B will multiply the 2 matrices and output the result. For this assignment, YOU CANNOT LETMATLAB MULTIPLY THE MATRICES FOR YOU! You must write the algorithm which calculates each ofthe matrix elements.Example output #1 for Part B:>> matrixThis program multiplies two m x m matrices A and B.Enter a value for m: 4Enter row 1 of A as an array: [ 1.3 2.1 2.5 5.1 ]Enter row 2 of A as an array: [ 2.4 3.2 4.1 0.8 ]Enter row 3 of A as an array: [ 2.3 1.2 1.4 1.5 ]Enter row 4 of A as an array: [ 3.3 0.7 0.6 1.3 ]Enter row 1 of B as an array: [ 1.2 1.3 1.4 1.5 ]Enter row 2 of B as an array: [ 2.8 2.3 2.2 1.5 ]Enter row 3 of B as an array: [ 1.5 0.5 1.1 2.2 ]Enter row 4 of B as an array: [ 1.8 1.4 0.9 0.5 ]The file matrix.txt will look like:A x B =_ _| 20.4 14.9 13.8 13.2 || 19.4 13.7 15.6 17.8 || 10.9 8.6 8.8 9.1 ||_ 9.2 8.0 8.0 8.0 _ |
2 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
将下列语句保存在一个文件名为matrix.m的Matlab脚本文件里:
clc;clear;
disp('This program multiplies two m x m matrices A and B.');
m=input('Enter a value for m: ');
A=zeros(m,m);B=A;C=A;
for i=1:m
str=sprintf('Enter row %d of A as an array: ',i);
A(i,:)=input(str);
end
for i=1:m
str=sprintf('Enter row %d of B as an array: ',i);
B(i,:)=input(str);
end
for i=1:m
for j=1:m
for k=1:m
C(i,j)=C(i,j)+A(i,k)*B(k,j);
end
end
end
str='AxB=';
dlmwrite('matrix.txt',str,'delimiter',' ','newline','pc','precision','%s');
dlmwrite('matrix.txt',C,'-append','delimiter',' ','newline','pc','precision','%.1f','roffset',1);
添加回答
举报
0/150
提交
取消