Simulataneous equation solver code

조회 수: 6 (최근 30일)
Tadiwa
Tadiwa 2022년 10월 11일
댓글: Tadiwa 2022년 10월 14일
Hi, I am trying to come up with a simultaneous equation solver that will ask a user for the number of simultanous equations to be solved and the number of coefficients in the simultaneous equations after which a for loop will be used to enter the number of coeffiecients for the number of equations.
Attached is the matlab code
% function for coefficient entry
function s = myfunc_Q2a(x)
s=zeros;
for i=1:x
s(i)=str2double(inputdlg('Enter coefficients: '));
end
end
% script that calls on the above function
g=msgbox('Equation is in the form: x1*a1 + x2*a2 + an*xn= b ');
waitfor(g)
n=str2double(inputdlg('Enter the number of simultaneous equations to be solved: '));
x=str2double(inputdlg('Enter the number of coefficients in the equation: '));
A=zeros;
B=zeros;
s=zeros;
for j=1:n
z(j)=myfunc_Q2a(x);
end
I am receiving an error that states left and right hand side have different number of elements, however when I choose
n=2 and x=1 I dont receive an error.
  댓글 수: 1
Ghazwan
Ghazwan 2022년 10월 11일
is it maybe x=1 is the only integer you are entering?
You have a counter i=1:x. x has to be an integer.

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

채택된 답변

Gowthami
Gowthami 2022년 10월 14일
Hi Tadiwa,
Here at
z(j)=myfunc_Q2a(x);
You are assigning the 'x'(number of coefficients) length elements array to 'z(j)' which is 1 element of a vector. Because of this you are encountering the error 'Unable to perform assignment because the left and right sides have a different number of elements.'
For example, if n = 2 and x = 3, The left side of this line of code refers to 1 element of z. The right side refers to a 3-element array.
As you mentioned you didn't receive any error when n = 2 and x = 1, because the left side of this line of code refers to 1 element of z and the right side refers to only 1 element. So, you are not encountering any error messages.
For resolve this issue, you may use a 2-D matrix. Please find the following code snippet for the same,
z=zeros(n,x);
for j=1:n
z(j,:)=myfunc_Q2a(x);
end
You may create a 2-D matrix where each row contains one of these 'x' length arrays or you could create a cell array.
I hope it helps.
  댓글 수: 1
Tadiwa
Tadiwa 2022년 10월 14일
This worked perfectly, many thanks

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by