How do I read and parse a .dat file in C? - c

I have a file called resistors.dat and I need to get my program to read and parse the values from the file into my program.
How would I read a file like this in C?
Read from the le resistors.dat (supplied on Blackboard) similarly to what you have done in Problem 2 of Lab 12. Each line in resistors.dat now represents one row: Ria, Rib and Ric (i = 1; 2; : : : ; n) of the circuit. Expand Problem 2 of Lab 12 to calculate the total resistance of the circuit. Hint: The total resistance is given by 1 R = 1 R1 + 1 R2 + 1 R3 + : : : + 1 Rn where Ri is the sum of resistances in one input row. In a loop, compute the sum of the inverse resistances 1=Ri. After the input has finished, compute the inverse of this sum to obtain the final result.
This is the content of resistors.dat:
64.35 35.52 85.37
90.43 12.99 80.40
98.37 32.63 78.42
3.82 82.74 52.61
3.75 72.47 49.05
96.73 16.07 23.46
48.15 36.62 83.64
51.96 27.19 22.38
4.18 46.07 91.21
96.94 8.17 50.45
0

There are several ways to accomplish this. I expect that your Resistors.dat file looks something like this:
r=1
r=20
r=22
r=2
I suggest you do something like this:
fopen to open the file, fgets in a while loop until the end of the file (!EOF), to read each line. Then use sscanf to parse each line.

Related

How to add additional zero arrrays

I have the following problem in my simulation.
A is an array 24 x 2. I am going to split it and get 4 or 12 array. It means that I group 6 or 2 array. It will be ok, if I use even "split" coefficient. If it is odd, I can"t split A.[ I can't group 5 or 7, because of 24/5=4*5 + 4 ( or 5*5 -1) or 24/7=7*3+3.
That's why I going to do the following:
If I have 24 x 2 and need group every 5 together:
block 1 : A(1,:), A(2,:),A(3,:),A(4,:),A(5,:)
block 2 : A(6,:), A(7,:),A(8,:),A(9,:),A(10,:)
block 3 : A(11,:), A(12,:),A(13,:),A(14,:),A(15,:)
block 4 : A(16,:), A(17,:),A(18,:),A(19,:),A(20,:)
block 5 : A(21,:), A(22,:),A(23,:),A(24,:), ?
As you can see the 5th block is not full, Matlab gives me an error. My idea is to create A(25,:)=0. For my simulation it will be ok.
I am going to simulate it as function:
A=rand(m,n)
w- # number of a vector that i would like group together ( in ex., it is `5`)
if mod(w,2)==0
if mod(m,2)==0
% do....
else
% remainder = 0
end
else
if mod(m,2)==0
% remainder = 0
else
%do...
end
I was going to simulate like above, but then I have noticed that it doesn't work. Because 24/10 = 2*10+4. So I should write something else
I can find the reminder as r = rem(24,5). As an example above, MatLab gives me r=4. then I can find a difference c= w-r =1 and after that, I don't know how to do that.
Could you suggest to me how to simulate such a calculation?
Determine the number of blocks needed, calculate the virtual amount of rows needed to fill these blocks, and add as many zero rows to A as the difference between the virtual and actual amount of rows. Since you didn't mention, what the actual output should look like (array, cell array, ...), I chose a reshaped array.
Here's the code:
m = 24;
n = 2;
w = 5;
A = rand(m, n)
% Determine number of blocks
n_blocks = ceil(m / w);
% Add zero rows to A
A(m+1:w*n_blocks, :) = 0
% Reshape A into desired format
A = reshape(A.', size(A, 1) / n_blocks * n, n_blocks).'
The output (shortened):
A =
0.9164959 0.1373036
0.5588065 0.1303052
0.4913387 0.6540321
0.5711623 0.1937039
0.7231415 0.8142444
0.9348675 0.8623844
[...]
0.8372621 0.4571067
0.5531564 0.9138423
A =
0.91650 0.13730
0.55881 0.13031
0.49134 0.65403
0.57116 0.19370
0.72314 0.81424
0.93487 0.86238
[...]
0.83726 0.45711
0.55316 0.91384
0.00000 0.00000
A =
0.91650 0.13730 0.55881 0.13031 0.49134 0.65403 0.57116 0.19370 0.72314 0.81424
0.93487 0.86238 0.61128 0.15006 0.43861 0.07667 0.94387 0.85875 0.43247 0.03105
0.48887 0.67998 0.42381 0.77707 0.93337 0.96875 0.88552 0.43617 0.06198 0.80826
0.08087 0.48928 0.46514 0.69252 0.84122 0.77548 0.90480 0.16924 0.82599 0.82780
0.49048 0.00514 0.99615 0.42366 0.83726 0.45711 0.55316 0.91384 0.00000 0.00000
Hope that helps!

Getting back empty arrays/ variables when uploading .txt file to Matlab

I am trying to load a .txt file with data to Matlab to use for some calculations. However, when I run the code the variables/arrays come back empty or blank.
Below I have the code I am using.
%% importing the data
% Open file in the memory
fileID = fopen('rainfall.txt');
% Read the txt file with formats: Integer, Integer, Float
% Treat multiple delimiters, which is "space" in here, as one. Put the data
% in a variable called chunk.
chunk = textscan(fileID,'%d %d %f','Delimiter',' ',...
'MultipleDelimsAsOne',1);
% Close file from the memory.
fclose(fileID);
% date
dt = chunk{:,1};
% hour
hr = chunk{:,2};
% precip
r = chunk{:,3};
% remove extra variables from Matlab workspace
clear fileID ans
In the Workspace tab in Matlab it shows chunk to be an empty 1x3 cell. This results in dt, hr, and r not having any values either and are listed as having a value of []. So my best guess is that something is going wrong with loading in the data to Matlab.
Also, here is small portion of the data I am working with. This is exactly how it is written in the .txt file as well.
STATION DATE HPCP
----------------- -------------- --------
COOP:132367 20040116 22:00 0.01
COOP:132367 20040116 23:00 0.01
COOP:132367 20040117 00:00 0.04
COOP:132367 20040117 01:00 0.02
COOP:132367 20040117 02:00 0.00
In the actual file I have a lot more data than what I have listed here, but this should give an idea of what the data looks like and how it's formatted.
From the textscan help page:
textscan attempts to match the data in the file to the conversion specifier in formatSpec. The textscan function reapplies formatSpec throughout the entire file and stops when it cannot match formatSpec to the data.
So the first problem is the title lines. You should discard them. For example, by manually reading 2 lines (using fgetl).
Next, you should make sure that the format matches the data. You tried reading 2 integers and a float but you also have the station name.
I think the following should be ok:
fileID = fopen('rainfall.txt');
l = fgetl(fileID);
l = fgetl(fileID);
chunk = textscan(fileID,'%s:%d %d %d %f','Delimiter',' ',...
'MultipleDelimsAsOne',1);

Print words from the corresponding line numbers

Hello Everyone,
I have two files File1 and File2 which has the following data.
File1:
TOPIC:topic_0 30063951.0
2 19195200.0
1 7586580.0
3 2622580.0
TOPIC:topic_1 17201790.0
1 15428200.0
2 917930.0
10 670854.0
and so on..There are 15 topics and each topic have their respective weights. And the first column like 2,1,3 are the numbers which have corresponding words in file2. For example,
File 2 has:
1 i
2 new
3 percent
4 people
5 year
6 two
7 million
8 president
9 last
10 government
and so on.. There are about 10,470 lines of words. So, in short I should have the corresponding words in the first column of file1 instead of the line numbers. My output should be like:
TOPIC:topic_0 30063951.0
new 19195200.0
i 7586580.0
percent 2622580.0
TOPIC:topic_1 17201790.0
i 15428200.0
new 917930.0
government 670854.0
My Code:
import sys
d1 = {}
n = 1
with open("ap_vocab.txt") as in_file2:
for line2 in in_file2:
#print n, line2
d1[n] = line2[:-1]
n = n + 1
with open("ap_top_t15.txt") as in_file:
for line1 in in_file:
columns = line1.split(' ')
firstwords = columns[0]
#print firstwords[:-8]
if firstwords[:-8] == 'TOPIC':
print columns[0], columns[1]
elif firstwords[:-8] != '\n':
num = columns[0]
print d1[n], columns[1]
This code is running when I type print d1[2], columns[1] giving the second word in file2 for all the lines. But when the above code is printed, it is giving an error
KeyError: 10472
there are 10472 lines of words in the file2. Please help me with what I should do to rectify this. Thanks in advance!
In your first for loop, n is incremented with each line until reaching a final value of 10472. You are only setting values for d1[n] up to 10471 however, as you have placed the increment after you set d1 for your given n, with these two lines:
d1[n] = line2[:-1]
n = n + 1
Then on the line
print d1[n], columns[1]
in your second for loop (for in_file), you are attempting to access d1[10472], which evidently doesn't exist. Furthermore, you are defining d1 as an empty Dictionary, and then attempting to access it as if it were a list, such that even if you fix your increment you will not be able to access it like that. You must either use a list with d1 = [], or will have to implement an OrderedDict so that you can access the "last" key as dictionaries are typically unordered in Python.
You can either:
Alter your increment so that you do set a value for d1 in the d1[10472] position, or simply set the value for the last position after your for loop.
Depending on what you are attempting to print out, you could replace your last line with
print d1[-1], columns[1]
to print out the value for the final index position you currently have set.

How to read file in matlab?

I have a txt file, and the content of the file is rows of numbers,
each row have 5 float number in it, with comma seperate between each number.
example:
1.1 , 12 , 1.42562, 3.5 , 2.2
2.1 , 3.3 , 3 , 3.333, 6.75
How can I read the file content into matrix in matlab?
So far I have this:
fid = fopen('file.txt');
comma = char(',');
A = fscanf(fid, ['%f', comma]);
fclose(fid);
The problem is that it's only give me the first line and when I
try to write the content of A I get this: 1.0e+004 * some number
Can someone help me please?
I guess that for the file I need to read it in a loop but I don't know how.
Edit: One more question: When I do output to A I get this:
A =
1.0e+004 *
4.8631 0 0 0 0.0001
4.8638 -0.0000 -0.0000 0.0004 0.0114
4.8647 -0.0000 -0.0000 0.0008 0.0109
I want the same values that in the file to be in the matrix, how can I make the numbers to be regular float and not formatted like this? Or are the numbers in the matrix actually float, but the output is just displayed like this?
MATLAB's built-in dlmread function would be a much easier solution for what you want to accomplish.
A = dlmread('filename.txt',',') % call dlmread and specify a comma as the delimiter
try with using importdata function
A = importdata(`filename.txt`);
It will solve your question.
EDIT
Alternative 1)
A = dlmread('test_so.txt',',');
The answer is surprisingly simple:
fid = fopen('depthMap.txt');
A = fscanf(fid, '%f');
fclose(fid);

Read from txt file to matrix after a specific expression

I wanted via matlab to read a table of data from a txt file after a specific expression and a number of non desired lines for example the AA.txt have:
Information about students :
AAAA
BBBB
1 10 100
2 3 15
! ! ! a number of lines
10 6 9
I have like information the expression 'Information about students', the number of skipped lines 2 and the number of columns 3 and rows 10 in desired matrix.
if I understand correctly, you wanna skip the first 3 lines (assuming them as headers) and then reading the rest.
I would follow this procedure:
fid = fopen(filename,'r');
A = textscan(fid,'%f %f %f','HeaderLines',3,'Delimiter','\r\n');
I currently do not have access to MATLAB, but I do believe it will work.

Resources