While looping running too many times

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 ExchangeLoops 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