User-defined function to perform Cramer's Rule

17 次查看(过去 30 天)
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