3x3 matrix with while loop

조회 수: 3 (최근 30일)
Benjamin Trivers
Benjamin Trivers 2020년 1월 21일
댓글: Jeremy 2020년 1월 21일
Produce a random 3x3 matrix A that is invertible and display it. Hint: Use a while-loop until you get one with non-zero determinant. To create a random matrix with N rows and M columns,use the MATLAB command rand(N,M).
I know how to produce the 3x3 matrix and how to display it. I am just a little confused on how to use the while-loop. Can someone please help me?
  댓글 수: 2
Alex Mcaulley
Alex Mcaulley 2020년 1월 21일
determinant = 0;
while determinant == 0
%Generate the random matrix
%Calculate the determinant of that matrix
end
Benjamin Trivers
Benjamin Trivers 2020년 1월 21일
I made a script for this one, and it just ran forever
I need it to stop if the determinate = 0

댓글을 달려면 로그인하십시오.

답변 (1개)

Jeremy
Jeremy 2020년 1월 21일
n = 3; m = 3;
A = zeros(n,m);
while det(A) == 0
A = rand(n,m);
end
  댓글 수: 4
Benjamin Trivers
Benjamin Trivers 2020년 1월 21일
just a little confused. the end of the question stated "Use disp to print matrices" so i thought i was looking for more than one matrix
sorry just confused
Jeremy
Jeremy 2020년 1월 21일
Using rand, it's fairly unlikely that you'll create a matrix whose determinant is 0. It'd probably be easier to get a 0 determinant with randi
That being said, maybe running this will help you see what's going on
n = 3; m = 3;
A = zeros(n,m);
k = 0;
while det(A) == 0
A = rand(n,m);
k = k + 1;
fprintf(1,'\nIteration Number %i \n',k)
fprintf(1,' Matrix A = \n\n')
disp(A)
fprintf(1,'The Determinant of Matrix A is: \n')
disp(det(A))
end
And if you wanted an (approximately) zero determinant:
n = 3; m = 3;
A = eye(n,m);
k = 0;
while abs(det(A)) > 0.001
A = rand(n,m);
k = k + 1;
fprintf(1,'\nIteration Number %i \n',k)
fprintf(1,' Matrix A = \n\n')
disp(A)
fprintf(1,'The Determinant of Matrix A is: \n')
disp(det(A))
end
Using randi instead:
n = 3; m = 3;
A = eye(n,m);
k = 0;
while det(A) ~= 0
A = randi([0 10],n,m);
k = k + 1;
fprintf(1,'\nIteration Number %i \n',k)
fprintf(1,' Matrix A = \n\n')
disp(A)
fprintf(1,'The Determinant of Matrix A is: \n')
disp(det(A))
end
I hope this helps

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by