I'm racking my brain and pounding my head against the wall because I can not figure out why such a simple while loop is running too many times. I'm writing a simple peace of code that will solve a system of equations when given the coefficients and constants. The code worked perfectly for about 2 hours then stopped after I tried to error proof the code. I undid my changes and still haven't gotten the code to work again.
Here's what I have written that's returning a weird amount of answers:
J = input('How many variables are there?\n');
A = input('Coefficients of Variables\n');
B = input('Constants\n');
c = A\B;
i = 0;
p = J-1;
while i <= p
i = i +1;
x = num2str(c(i,1));
fprintf('the %d variable is %d\n',i,x)
end
Here's the output when J = 2 A = [4 5; 2 1] and B = [2;3]
the 1 variable is 50
the 46 variable is 49
the 54 variable is 54
the 55 variable is the 2 variable is 45
the 49 variable is 46
the 51 variable is 51
the 51 variable is 51

 채택된 답변

Birdman
Birdman 2018년 4월 4일
편집: Birdman 2018년 4월 4일

0 개 추천

Change the following lines
x = num2str(c(i,1));
fprintf('the %d variable is %d\n',i,x)
to
x = string(c(i,1));
fprintf('the %d variable is %s\n',i,x)
It was not running too many times. Because of the wrong formatSpec used in fprintf, it seemed to be running too many times. Actually, it printed out the your char x element by element.

댓글 수: 3

Zachry Rankin
Zachry Rankin 2018년 4월 4일
Oh, I didn't remove num2str when starting from scratch. Thank you!
Zachry Rankin
Zachry Rankin 2018년 4월 4일
Do you have any idea why it would've worked the first couple times I used the code after adding 'num2str' without changing the second %d to %s?
Birdman
Birdman 2018년 4월 4일
It might have happened because of x being one element character.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2018년 4월 4일

댓글:

2018년 4월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by