Azzera filtri
Azzera filtri

User-defined function to perform Cramer's Rule

17 visualizzazioni (ultimi 30 giorni)
Jacob Forbes
Jacob Forbes il 11 Mar 2021
Modificato: Rik il 14 Mar 2021
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 Commenti
Jan
Jan il 11 Mar 2021
Please mention why you think, that there is something going wrong.
Rik
Rik il 14 Mar 2021
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.

Accedi per commentare.

Risposte (1)

James Tursa
James Tursa il 11 Mar 2021
Modificato: James Tursa il 11 Mar 2021
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.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by