i have a problem rounding a loop
Mostrar comentarios más antiguos
so if i write a loop that and it gives me a answer of .0215243225 you know just a huge number but i wanted to round it to the .0001, .001, .01. how would i do that i m using a for statment for a loop
6 comentarios
John D'Errico
el 6 de Nov. de 2019
Editada: John D'Errico
el 6 de Nov. de 2019
What is huge about the number you gave? I guess, compared to avogadro's number, it is huge. ;-)
But why in any remote scenario would you use a loop to do this, instead of using roundn? Why would you use a loop in any case?
Ok, this will do...
for loopindex = 1:1
x = roundn(x,2);
end
But it seems a bit of overkill.
Seriously, if this is not homework, then you need to answer why you would possibly not use roundn.
If it is homework, then you need to answer why we should be doing your homework for you, and even given that, why we would use a loop anyway.
Raul Castillo
el 6 de Nov. de 2019
John D'Errico
el 6 de Nov. de 2019
Editada: John D'Errico
el 6 de Nov. de 2019
I'm still a little confused. Let me give an example. I'll compute a simple result, doing it in a loop. Then I'll round the result to 2 decimal places, still inside the loop.
n = 5;
result = zeros(1,n); % preallocate vectors like this
for i = 1:n
result(i) = sin(i);
% rounding it, to 2 digits after the decimal
result(i) = round(result(i),2);
end
result
result =
0.84 0.91 0.14 -0.76 -0.96
Admittedly, I never needed to use a loop to do any of this, but to show it gave the desired result...
[1:5;sin(1:5);round(sin(1:5),2)]
ans =
1 2 3 4 5
0.84147 0.9093 0.14112 -0.7568 -0.95892
0.84 0.91 0.14 -0.76 -0.96
As you can see, the round operation inside the loop did what it is supposed to do.
But I have a very funny feeling that this is not what you are really asking.
Raul Castillo
el 6 de Nov. de 2019
Shubham Gupta
el 7 de Nov. de 2019
Editada: Shubham Gupta
el 7 de Nov. de 2019
Do you want to round the value to significant digits, which will change in a loop? For e.g.
a_answer= .0215243225;
for i = 2:5
output = round(a_answer,i)
end
% You will get output
output =
0.02
output =
0.022
output =
0.0215
output =
0.02152
It's basically the same method as mentioned by John, only instead of looping on values I looped it for significant digits.
Steven Lord
el 7 de Nov. de 2019
You can do that without manually adjusting the number of digits by specifying the 'significant' option in your call to round.
>> a_answer= .0215243225;
>> round(a_answer, 3, 'significant')
ans =
0.0215
>> b = pi/1000;
>> round(b, 3, 'significant')
ans =
0.00314
>> round(b, 5)
ans =
0.00314
Respuestas (0)
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!