MATLAB: Round double value to 2 decimal

arraydecimaldoublelooproundsprintf

Hi all,
I'm trying to round an array of double values to 2 decimals.
This is my code:
for k=1:n,
y(k)=k*st;
y(k)= sprintf('%0.2f', y(k));
x(k) = sqrt(d^2+(2*y(k))^2)-d;
x(k)= sprintf('%0.2f', x(k));
end
I got the following error message:
In an assignment A(I) = B, the number of elements in B and I must be the same.
BTW! the value n is 10.
I want the arrays y and x with 2 decimal values. Ex: 1.23
Thanks a lot.
Raúl. In an assignment A(I) = B, the number of elements in B and I must be the same.

Best Answer

The reason you're getting the error is that sprintf creates a char array -- in this case, a 1-by-4 char array made up of the 4 characters '1', '.', '2', and '3'. But your assignment is to a single element y(k).
Possible solutions are to index into the kth row of a char array, which you should keep separate from your double array y (otherwise you'll get another error), or to use cell arrays as Wouter suggests, or to just round everything as doubles and avoid strings altogether (as Wouter also suggests).
I'd recommend the last approach. You can always display things with sprintf or fprintf at the end, and this can be done without a for-loop: fprintf(1,'%0.2f\n',x)