-1

I'm using a function in MATLAB for the first time. The function body is working properly., but when it is called from a program it giving an error.

The function is:

function f = adjust(value)
if value < 0
  s = -1;
  value = -value;
else
  s = 1;
end

b = floor(value);
value = value-b;
value = s*value;

f = sprintf('%.14f', value);

Main program is

x(1) = 0.3;
y(1) = -0.4;
a = 36;
for n = 2:16 
   temp = a*(y(n-1)-x(n-1));
   x(n) = adjust(temp);
end

I want to generate a number of values with precision 1e-14. When I run the program, I get the error

???  In an assignment  A(I) = B, the number of elements in B and
I must be the same.

Error in ==> one at 6
    x(n) = adjust(temp);"

I don't know what to do with this. Please help me if you can.

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
MSD
  • 109
  • 1
  • 2
  • 12
  • Do you happen to have a variable in your main program called `adjust`? You can check this with the `whos `command. – Rody Oldenhuis Sep 02 '13 at 10:19
  • inside the loop, display the values of `n`, `temp`, `y(n-1)`, `x(n-1)`, `a`, and `adjust(temp)` *before* the line `x(n) = ...`. I think this will show where the problem is. – Rody Oldenhuis Sep 02 '13 at 10:23

1 Answers1

6

Your function is returning f as the output of sprintf, which is a char array. You can't put this into x, because x has already been defined as containing doubles with x(1)=0.3;

You may want to use sprintf to print the value to screen so you can check it, but your function should be returning a number, value.

ETA: As Rody explained in the comments, format can be used to change how Matlab displays numbers, but the precision does not change. Similarly, sprintf can control the format but it doesn't change the value itself. Try these lines at the command line:

format short
value = 3.000000000012
format long
value
nkjt
  • 7,825
  • 9
  • 22
  • 28
  • thats the exact problem.but how to solve this by keeping the precision 10^-14..any ideas??? – MSD Sep 02 '13 at 10:31
  • 1
    @user2689061: MATLAB's precision is always the best possible (~`1e-16` determined by IEEE754 `double`). So just returning `value` will already meet your `1e-14` demand. Now, how MATLAB *displays* values depends on your setting of `format`. – Rody Oldenhuis Sep 02 '13 at 10:42