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

 Réponse acceptée

Birdman
Birdman le 4 Avr 2018
Modifié(e) : Birdman le 4 Avr 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 commentaires

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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by