help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Problem using fscanf


From: Bård Skaflestad
Subject: Re: Problem using fscanf
Date: Fri, 15 Apr 2011 12:23:50 +0200

On Fri, 2011-04-15 at 11:37 +0200, Utherr13 wrote:
> I don't know how to use  load, help manual is ambiguous and not helping. I
> want some examples.
> 
>  # Create test data file: 
>    x = floor(100 * rand([100, 2]));  # create some data 
>    f = fopen("data.txt", "w");       # error checking omitted 
>    fprintf(f, "%d %d\n", x .');      # output data to file 
>    fclose(f); 
> 
> whooo... hold one.. my data is not like that. It has 2,3 or 4 spaces between
> first column and second.

For the purpose of "fscanf" your data is *exactly* like that.  A single
space in the scan template is interpreted as an arbitrary (positive)
number of space-like characters.  See for instance

http://www.gnu.org/software/octave/doc/interpreter/Formatted-Input.html

or any text book on C.

> 
> The piece of code that you supplied to me only gets the first row.
> 
> Here's my complete code that doesn't work:
> 
> function y=dens_energy()
>       % a = 3
>       % besseli(0,3) = 4,8808
>       f=fopen('sunspot.dat','r');
>       a=zeros(100,2);
>       for i=1:100
>               z = fscanf(f,"%d",1);   %first column is useless
>               a(i) = fscanf(f,"%d",1);
>               disp(a(i));
>       endfor
> endfunction

Right.  So you're (attempting) to read lines of integers (%d) from the
file sunspot.dat

> 
> a part of sunspot.dat: 
> 
> 1701   11.0
> 1702   16.0

except sunspot.dat does not contain (only) integers.  The result is
input failure.  You need to use a scan template for floating point
conversion to read this data.  Try this:

   t = fscanf(f, "%f", [2, inf]) .';
   a = t(:,2);

The "%f" template converts integer data too.

Still, using "load" is probably easier for this task as you don't have
to remember to close the file once you're done with it:

   a = load("sunspot.dat");
   a = a(:,2);


Sincerely,
-- 
Bård Skaflestad <address@hidden>
SINTEF ICT, Applied Mathematics



reply via email to

[Prev in Thread] Current Thread [Next in Thread]