[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
- Re: Problem using fscanf, (continued)
- Re: Problem using fscanf, Bård Skaflestad, 2011/04/14
- Re: Problem using fscanf, Utherr13, 2011/04/15
- Re: Problem using fscanf, Bård Skaflestad, 2011/04/15
- octave from java, frank buloup, 2011/04/15
- Re: octave from java, George Kousiouris, 2011/04/15
- Re: octave from java, Kim Hansen, 2011/04/15
- Re: octave from java, Utherr13, 2011/04/15
- Re: octave from java, frank buloup, 2011/04/15
- Re: octave from java, Kim Hansen, 2011/04/17
- Re: Problem using fscanf, Utherr13, 2011/04/15
- Re: Problem using fscanf,
Bård Skaflestad <=
- Re: Problem using fscanf, Bård Skaflestad, 2011/04/15
- Re: Problem using fscanf, Jordi Gutiérrez Hermoso, 2011/04/15