Convert csv file to mat file - matlab

I have a csv file as follows:
StringA,StringB ...
1.234,13.45 ...
I want to convert this into a .mat file extension but when I try to read the csv file, it throws and error due to the fact that I have strings in the first row. This makes it difficult to directly convert to a mat file as I also want the headers in my mat file. How would I go about doing this?

Given your file format, you can use importdata() like this:
M = importdata('myfile.txt', ',', 1);
The header will be saved in M.colheaders, the data will be stored in M.data.
Please have a look at the documentation for further information and a working example.

Related

How to append a file to an existing zip file/folder

Is there a way to append a file to an existing zip file/folder?
zip(zipfilename,filenames) would overwrite the original zipfilename.
I am using Windows 10 in case that makes a difference.
system(['powershell.exe -ExecutionPolicy Bypass Compress-Archive -update ',...
filename,' ',...
zipfilename]);
works.
Alternatively, as #Rotem pointed out, and in some situations more suitable, we can use Java's ZipOutputStream as long as we convert data to binary first.
If we start with a file test.csv, then the contained string can be read into an uint8 array by
filename = 'test.csv'; % change filename as needed.
fid = fopen(filename, 'r');
data = fread(fid , '*uint8');
fclose(fid );
If we start with data in a Matlab Workspace, we need to convert the data into the format we desire in the eventual output file and then convert it to binary. For example, if the desired compressed file is a .csv file, in other words, formatted text, we can prepare the string output with sprintf and convert it to the corresponding uint8 array such as
data = uint8(sprintf('%d, %d\r\n', [1,2;3,4]));
Following the above, one can use Java's ZipOutputStream to output to an existing zip file. Example below.
filename='test.csv'; % change filename of zip entry as needed
zipfilename='test.zip'; % change filename as needed
fos = java.io.FileOutputStream(zipfilename);
zos = java.util.zip.ZipOutputStream(fos);
ze = java.util.zip.ZipEntry(filename);
% zos.setLevel(9); % optional
zos.putNextEntry(ze);
zos.write(data, 0, numel(data));
zos.finish;
zos.close;
The benefit of this approach is that, if the data starts off in the current Matlab Worksapce, no additional file needs to be created, which would have required additional i/o use 3 times (in the above example, write test.csv, read csv, delete csv).
Another benefit is that the this method does not require powershell which is OS dependent -- not available in earlier Windows versions for example.
If the data starts off in an external file with Windows 10, as specified in the OP, then the 1st method is more expedient.
Note: Additional information on reading from the zip file or reading file list from zip file can be found here and here.

Reading a file from a different directory in matlab

My matlab function is in a folder that contains the main project and the other functions of the code. However, the data is stored in a folder withing the main one named "data" and inside the specific dataset that i want, for example "ded4" in this example. I can't figure out how to open the text file that I want without changing the file to the main folder. The code I have so far is:
function[Classify] = Classify(logDir)
%%%%logDir='ded014a04';
Directory = ['data/' logDir '/']
Filename = [logDir '-fixationsOffSet']
File_name = fullfile(Directory,Filename)
File = fopen(File_name,'r')
end
The code is in the 'dev' folder, I think my path is correct because when I do
open(File_name)
it opens.
Thanks for the help
If you want to open the file in the editor, use
open(File_name)
If you want to read data from the file, you can use
dlmread(File_name) % Read ASCII delimited file.
or
C = textscan(File,'FORMAT') % Read formatted data from text file or string.
or more low-level using fscanf, e.g., if the file contains three columns of integers you do the following: Read the values in column order, and transpose to match the appearance of the file: (from the help of fprintf)
fid = fopen('count.dat');
A = fscanf(fid,'%d',[3,inf])';
fclose(fid);

Error code in importing multiple csv files from certain folder using matlab

I am really a newbie in matlab programming. I have a problem in coding to import multiple csv files into one from certain folder:
This is my code:
%% Importing multiple CSV files
myDir = uigetdir; %gets directory
myFiles = dir(fullfile(myDir,'*.csv')); %gets all csv files in struct
for k = 1:length(myFiles)
data{k} = csvread(myFiles{k});
end
I use the code uigetdir in order to be able to select data from any folder, because I try to make an automation program so it would be flexible to use by others. The code that I run only look for the directory and shows the list, but not for merging the csv files into one and read it in "import data". I want it to be merged and read as one file.
My merged file should look like this with semicolon delimited and consist of 47 csv files merged together (this picture is one of the csv file I have):
my merged file
I have been working for it a whole day but I find always error code. Please help me :(. Thank you very much in advance for your help.
As the error message states, you're attempting to reference myFiles as a cell array when it is not. The output of dir is a structure, which cannot be indexed like a cell array.
You want to do something like the following:
for k = 1:numel(myFiles)
filepath = fullfile(myFiles(k).folder, myFiles(k).name);
data{k} = csvread(filepath);
end

Octave: create .csv files with varying file names stored in a sub folder

I have multiple arrays with string data. All of them should be exported into a .csv file. The file should be saved in a subfolder. The file name is variable.
I used the code as follows:
fpath = ('./Subfolder/');
m_date = inputdlg('Date of measurement [yyyymmdd_exp]');
m_name = inputdlg('Characteristic name of the expteriment');
fformat = ('.csv');
fullstring = strcat(fpath, m_date,'_', m_name, fformat);
dlmwrite(fullstring,measurement);
However, I get an error that FILE must be a filename string or numeric FID
What's the reason?
Best
Andreas
What you are asking to do is fairly straightforward for Matlab or Octave. The first part is creating a file with a filename that changes. the best way to do this is by concatenating the strings to build the one you want.
You can use: fullstring = strcat('string1','string2')
Or specifically: filenameandpath = strcat('./Subfolder/FixedFileName_',fname)
note that because strings are pretty much just character arrays, you can also just use:
fullstring = ['string1','string2']
now, if you want to create CSV data, you'll first have to read in the file, possibly parse the data in some way, then save it. As Andy mentioned above you may just be able to use dlmwrite to create the output file. We'll need to see a sample of the string data to have an idea whether any more work would need to be done before dlmwrite could handle it.

Saving strings from the input .txt filename - MATLAB

Via textscan, I am reading a number of .txt files:
fid1 = fopen('Ev_An_OM2_l5_5000.txt','r');
This is a simplification as in reality I am loading several hundred .txt files via:
files = dir('Ev_An*.txt');
Important information not present within the .txt files themselves are instead part of the filename.
Is there a way to concisely extract portions of the filename and save them as strings/numbers? For example saving 'OM2' and '5000' from the above filename as variables.
fileparts appears to require the full path of the file rather than just defaulting to the MATLAB folder as with textscan.
It depends on how fixed your filename is. If your filename is in the string filename, then you can use regexp to extract parts of your filename, like so:
filename = 'Ev_An_OM2_l5_5000.txt'; %or whatever
parts = regexp(filename,'[^_]+_[^_]+_([^_]+)_[^_]+_([^\.]+)\.txt','tokens');
This will give you parts{1}=='OM2' and parts{2}=='5000', assuming that your filename is always in the form of
something_something_somethingofinterest_something_somethingofinterest.txt
Update:
If you like structs more than cells, then you can name your tokens like so:
parts = regexp(filename,'[^_]+_[^_]+_(?<first>[^_]+)_[^_]+_(?<second>[^\.]+)\.txt','names');
in which case parts.first=='OM2' and parts.second=='5000'. You can obviously name your tokens according to their actual meaning, since they are important. You just have to change first and second accordingly in the code above.
Update2:
If you use dir to get your filenames, you should have a struct array with loads of unnecessary information. If you really just need the file names, I'd use a for loop like so:
files = dir('Ev_An*.txt');
for i=1:length(files)
filename=files(i).name;
parts = regexp(filename,'[^_]+_[^_]+_(?<first>[^_]+)_[^_]+_(?<second>[^\.]+)\.txt','tokens');
%here do what you want with parts.first, parts.second and the file itself
end