Loading variables from ascii file - matlab

I am trying to load variables from a .dat file I have created.
The file is in the following format:
x = 1
y = 2
z = 3
I understand that if the file was in the format:
1 2 3
I could use
s = load(filename.dat)
and it would create an array with name 'S' storing all the numbers in the file.
However, from the first format I showed, I would like each stored as a separate variable.
I know I could do this with a .MAT file but this isn't really optimal to my requirements because it needs to be easily edited, preferably with notepad or another word processor.

Try textread function:
[varNames, varValues] = textread('tmp.txt', '%s%f', 'whitespace','\n', 'delimiter','=');
disp(varNames);
'x '
'y '
'z '
disp(varValues);
1
2
3

Related

Import a variable from .mat and export to CSV

I have a .mat file which contains a struct (called wiki),
in which there is a field called full_path containing data as follows:
ans =
Columns 1 through 4
{'17/10000217_198…'} {'48/10000548_192…'} {'12/100012_1948-…'} {'65/10001965_193…'}
Columns 5 through 8
{'16/10002116_197…'} {'02/10002702_196…'} {'41/10003541_193…'} {'39/100039_1904-…'}
and so on
How can I create a .csv file with the data present in the curly braces?
This is quite a common problem, which requires very basic functions:
wiki = struct2array(load('wiki.mat', 'wiki'));
fid = fopen('q52688399.csv', 'w');
fprintf(fid,'%s\n', wiki.full_path{:});
fclose(fid);
The above will produce a ~2MB text tile containing a single column of strings.

How do I read comma separated values from a .txt file in MATLAB using textscan()?

I have a .txt file with rows consisting of three elements, a word and two numbers, separated by commas.
For example:
a,142,5
aa,3,0
abb,5,0
ability,3,0
about,2,0
I want to read the file and put the words in one variable, the first numbers in another, and the second numbers in another but I am having trouble with textscan.
This is what I have so far:
File = [LOCAL_DIR 'filetoread.txt'];
FID_File = fopen(File,'r');
[words,var1,var2] = textscan(File,'%s %f %f','Delimiter',',');
fclose(FID_File);
I can't seem to figure out how to use a delimiter with textscan.
horchler is indeed correct. You first need to open up the file with fopen which provides a file ID / pointer to the actual file. You'd then use this with textscan. Also, you really only need one output variable because each "column" will be placed as a separate column in a cell array once you use textscan. You also need to specify the delimiter to be the , character because that's what is being used to separate between columns. This is done by using the Delimiter option in textscan and you specify the , character as the delimiter character. You'd then close the file after you're done using fclose.
As such, you just do this:
File = [LOCAL_DIR 'filetoread.txt'];
f = fopen(File, 'r');
C = textscan(f, '%s%f%f', 'Delimiter', ',');
fclose(f);
Take note that the formatting string has no spaces because the delimiter flag will take care of that work. Don't add any spaces. C will contain a cell array of columns. Now if you want to split up the columns into separate variables, just access the right cells:
names = C{1};
num1 = C{2};
num2 = C{3};
These are what the variables look like now by putting the text you provided in your post to a file called filetoread.txt:
>> names
names =
'a'
'aa'
'abb'
'ability'
'about'
>> num1
num1 =
142
3
5
3
2
>> num2
num2 =
5
0
0
0
0
Take note that names is a cell array of names, so accessing the right name is done by simply doing n = names{ii}; where ii is the name you want to access. You'd access the values in the other two variables using the normal indexing notation (i.e. n = num1(ii); or n = num2(ii);).

Insert String in a CSV file matlab

how do I insert a string into a csv file in matlab. i used this code to write some data and create my csv file:
and here is the output of the code:
I'm trying to insert some text in the first 2 columns before the numerical data..
thanks in advance :)
There are several approaches are possible here.
Let's take a look at some of them:
If you need to add string to your csv file.
For example, I create some csv file like your:
q = [1 2 3 4 5 6 7];
csvwrite('csvlist4.csv',q,2,0);
All troubles is to add some string to csv - it's because we need to combine numeric and text data. There are no good functions for it in Matlab except low levels:
c = 'some big text';
fid = fopen('csvlist4.csv','r+');
fprintf(fid,c);
How it works: the data in csv is an array. I put data in 3rd row, so first and second is an empty but they have ','. When you use fprintf it will replace this , with your text. So if text is too long it will overwrite your data.
How to avoid this?
Easiest way - is to do it with help of xlswrite function. For your example:
txt = cell(size(Q))
txt{1} = 'this is your text'
X = [txt; num2cell(Q)]
xlswrite('new.xlsx',X)
Result:
Important moment here: number of cell for text must be the same as your data. But I filled with the text only first cell in my example.
And the one more way: read csv file, modify it's data and write to csv:
csvwrite('csvlist4.csv',a,2,0);
m = csvread('csvlist4.csv');
fid = fopen('csvlist4.csv','w');
c = 'your text'
fprintf(fid, c); fprintf(fid, '\n');
fclose(fid);
dlmwrite('csvlist4.csv', m(3:end,:), '-append');
Of course you can use cell array instead c and so on and so on.
Hope it helps!

export matlab file to txt file with delimiter

I have 2 column vectors named t and f which looks like this:
t=
1
2
3
4
5
and
f=
10
20
30
40
50
I would like to make a txt file which looks like this:
1,10
2,20
3,30
4,40
5,50
I tried the next codes but nothing worked so far:
vec_char=char(44*ones(1,length(t)))'; %vector of comma's
filename=fopen('functiondata.txt','w');
formatspec='%d %s %d\n';
data={t,vec_char,f};
[nrows,ncols]=size(data);
for row=1:nrows
fprintf(filename,formatspec,data{row,:});
end
fclose(filename);
if theres something better to do, it would be nice.
I highly suggest you use dlmwrite. This takes a matrix as well as the name of the file you want to write and writes it to file. The default delimiter that separates the numbers are commas, which is what you want.
Try this:
t = (1:5).'; f = (10:10:50).'; %// Your data
dlmwrite('functiondata.txt', [t f]);
Opening up functiondata.txt, we get this:
1,10
2,20
3,30
4,40
5,50
Note
If you are using Windows, the new line character will not be put in properly when dlmwrite is called. You need to specifically state this when calling dlmwrite:
dlmwrite('functiondata.txt', [t f], 'newline', 'pc');

Creating variables with numbers from filename

I have a folder full of xls files, named data_00001 through data_10000. Each file has a dozen or so identically named tabs full of RV's. I am interested in reading all files and tabs and creating histograms of the RV's.
Is there a way to read in the last 5 digits of the file names and attached them to each tab name (which I saved as a variable)?
I used regexp to extract the number as a string and converted it to a double, and I used a for loop to save variable X{1,k}. How can I incorporate the saved double into this variable?
Are you looking for something like this?
filenames = ['data_00001','data_10000'];
nums = regexp(filenames, '[0-9]+', 'match');
tag = 'TAG';
for i=1:size(nums,2)
eval(['A_' tag '_' sprintf("%s",nums{1,i}) ' = zeros(1)']);
end
It creates matrices (zero in this case) with variable names
A_TAG_00001 = 0
A_TAG_10000 = 0