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

 Accepted Answer

Birdman
Birdman on 4 Apr 2018
Edited: Birdman on 4 Apr 2018
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 Comments

Oh, I didn't remove num2str when starting from scratch. Thank you!
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?
It might have happened because of x being one element character.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 4 Apr 2018

Commented:

on 4 Apr 2018

Community Treasure Hunt

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

Start Hunting!