필터 지우기
필터 지우기

User-defined function to perform Cramer's Rule

조회 수: 17 (최근 30일)
Jacob Forbes
Jacob Forbes 2021년 3월 11일
편집: Rik 2021년 3월 14일
I'm tasked with writing a function that will check if a coefficient matrix A is square and has a nonzero determinant, then compute the Cramer's rule matrix from that. I'm struggling to figure out where my code is going wrong.
function [A, b] = mycramersrule(issquare, sol_x)
A=[];
b=[];
issquare = (size(A,1) == size(A,2));
for i = 1:size(b,1)
if det(A)~=0 && issquare == (size(A,1) == size(A,2))
A_i=A;
A_i(:,i)=b(:);
sol_x=[det(A_i)/det(A)]
else
sol_x=[]
end
end
end
  댓글 수: 2
Jan
Jan 2021년 3월 11일
Please mention why you think, that there is something going wrong.
Rik
Rik 2021년 3월 14일
I recovered the removed content from the Google cache (something which anyone can do). Editing away your question is very rude. Someone spent time reading your question, understanding your issue, figuring out the solution, and writing an answer. Now you repay that kindness by ensuring that the next person with a similar question can't benefit from this answer.

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

답변 (1개)

James Tursa
James Tursa 2021년 3월 11일
편집: James Tursa 2021년 3월 11일
You made a good start. A and b should be inputs to your function, not outputs. Similarly, issquare is an internal test and sol_x should be an output, not input. You have this written backwards. It should be:
function sol_x = mycramersrule(A,b)
% A=[]; get rid of this line
% b=[]; get rid of this line
Your det(A) and issquare test only needs to be done once, prior to the loop, not inside the loop. And you don't need to keep a variable for this. So the next part of your code should be:
if( det(A)~=0 && size(A,1) == size(A,2) )
% your for-loop goes here, no testing needs to be done inside the for-loop
else
sol_x = [];
end
And inside your for-loop, you need to assign each individual result to an element of sol_x, not the whole variable. So:
sol_x(i) = det(A_i)/det(A);
Try to make these corrections and run your code. If you continue to have problems, post the new code and ask further questions.

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by