Adding Symbolic equations using while loops
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I am attempting to create a matlab version of the KCL equation. I can't figure out a way to loop through all the possible equations and ADD them together.. as symbolic equations. I eventually need to end up with a system of equations that I can set equal to zero and then Solve. Currently this code won't even give me a single equation. It just spits out 0 unitl infinity. Any ideas on how to fix this? I dont want to have to hard code the addition of all of these possible outcomes. Thanks!!
nodes = sym('n',[1 10])
nodes(1,1)=0;
disp(nodes)
answer=inputdlg({'nodes'});
n=str2double(answer(1,1));
Resistance=Inf(n);
A=1;
B=0;
C=0;
i=0
while A < n
B = B+1;
C = C+1;
while B < n
B = B+1;
answer =inputdlg(['Enter resistance between ',num2str(A),' and ',num2str(B),' or enter "I" for infinite resistance.']);
if strcmp(answer, 'I')
i = i+1;
else
Resistance(A,B) = str2double(answer)
Resistance(B,A) = str2double(answer)
end
end
A = A+1;
B = C;
end
disp(Resistance)
Col =1;
Row =0;
C=0;
while Col < n
Row = Row+1;
C = C+1;
while Row < n
EquationExample = (nodes(1,Col)-nodes(1,Row))/(Resistance(1,Row))
disp(EquationExample)
end
Col = Col+1;
Row = C;
end
0 Commenti
Risposte (1)
Ayush Aniket
il 10 Mag 2024
Hi Emma,
In your inner 'while' loop for calculating 'EquationExample', you're missing an increment for 'Row' variable within the loop. This causes an infinite loop because the condition 'Row < n' never becomes false. To fix this, you need to increment 'Row' inside the loop.
Additionally, the process for accumulating equations is not right. With your current implementation, the equations get overwritten. The correct way should to be to add the current equation and then store it in an array as show below:
equations = sym([]); % Initialize an empty array to hold the equations
for Col = 1:n
% Initialize the current equation to 0
currentEquation = 0;
for Row = 1:n
if Resistance(Col, Row) ~= Inf % Check if resistance is not infinite
% Add the current term to the equation
currentEquation = currentEquation + (nodes(Col) - nodes(Row)) / Resistance(Col, Row);
end
end
% Add the constructed equation for the current node to the equations array
equations = [equations, currentEquation == 0];
end
disp(equations)
Once the equations are accumulated you can use the 'solve' function to solve them to find node voltages. Refer to the documentation below:
0 Commenti
Vedere anche
Categorie
Scopri di più su Symbolic Math Toolbox in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!