Failed to plot graph of two arrays in Octave

I have created two arrays in octave using a for loop and I want to create a graph using the data of the two arrays. But it showed an error " invalid value for array property "xdata"" and displayed an empty graph.

for i=1:16 x=1+(10^6)*2 h=1/(10.^i) fdd1=(sin(1+h)-sin(1))/h error_f1=fdd1-cos(1) endfor **fplot(loglog(h,error_f1));** 
Am I making mistakes in plotting the graph? May I know how to solve this problem? asked Feb 16, 2015 at 11:27 123 2 2 gold badges 4 4 silver badges 17 17 bronze badges

1 Answer 1

Yes, you are doing all the possible mistakes in that snippet.

  1. your variables h and error_f are cell arrays. The function loglog takes numeric arrays. I believe your specific error comes from there. You can convert them with cell2mat as in loglog (cell2mat (h), cell2mat (error_f1)) but I would argue that would still be incorrect since you should have never created a cell array in the first place (see point 4).
  2. your data has non-positive values which you can't plot with logarithmic scale.
  3. the fplot function takes a function handle as argument. Why are you passing a figure handle (the output of loglog ) to it?
  4. Octave is a language designed around vectorized operations. It's syntax has a strong emphasis and you will suffer if you don't. You should not have a for loop for this. Just remove your indexing and make your multiplication and division element-wise. This also fixes problem 1 since you will end up with a numeric array
r = 1:16; x = 1 + (10^6)*2; h = 1 ./ (10.^r); fdd1 = (sin (1+h) - sin (1)) ./ h; error_f1 = fdd1 - cos(1); 

Rule of thumb in Octave: if you ever see a for loop, chances are you are doing it wrong.