Converting .mat file to .csv file results in an error? - matlab

I've looked online and have done the following to convert a .mat file into a .csv file, but I keep seeing an error. This is what I've tried:
FileData = load('mydata.mat');
csvwrite('weights.csv', FileData);
However I keep seeing the following error in matlab:
Undefined function 'real' for input arguments of type 'struct'.
Error in dlmwrite (line 189)
str = sprintf('%.*g%+.*gi',precn,real(m(i,j)),precn,imag(m(i,j)));
Error in csvwrite (line 42)
dlmwrite(filename, m, ',', r, c);
Here's a bit more information about my mat file
Would appreciate some help!

csvwrite works with matrices, not struct. You need to convert the struct into a matrix first.
Alternatively, if you're using newer versions of MATLAB and your struct members are all data arrays, you can also use T = struct2table(FileData) and then writetable(T,'myData.csv','Delimiter',',')

Related

Matlab error while creating csv file from image set using imread and csvwrite

I want to convert a set of images into a csv file. I was working with Matlab and I need each row corresponding to one image. I tried to do it with the following code
I=imread(c{n});
csvwrite('C:\Users\HP\Desktop\test.csv',I(:).','-append'); % c{n} contains the name of image files to be taken
but I am getting the following error
Error using dlmwrite (line 112)
Invalid attribute tag: ,.
Error in csvwrite (line 42)
dlmwrite(filename, m, ',', r, c);
Error in Untitled (line 7)
csvwrite('C:\Users\HP\Desktop\test.csv',I(:).','-append');
but if I try to do it without the '-append' there is no error.
How to change the code such that it takes all the images at once and produces a csv file with the single execution of the code.
csvwrite is meant for writing comma separated values, so adding that ',' is wrong. Then you have put a dot('.') after I(:), which is also wrong. I think you should better use dlmwrite if you want to append the files. It would go like dlmwrite('C:\Users\HP\Desktop\test.csv',I(:)','-append') (since you want each image as one row, you need to transpose the array).
For using this on all images, start by reading all the images into a cell array & then you use cellfun(#(x) dlmwrite('C:\Users\HP\Desktop\test.csv',x(:)','-append'),a). Or for a much simpler version just run the lines in your code inside a for loop.

Issue when writing matrix to file using csvwrite

I am trying to output the matrix to a CSV file (comma separated) using this function csvwrite('myMatrix.dat',L); ( where L is square matrix) I got this error:
>> csvwrite('myMatrix.dat',L);
Error using sprintf
Function is not defined for sparse inputs.
Error in dlmwrite (line 169)
str = sprintf(format,m(i,:));
Error in csvwrite (line 42)
dlmwrite(filename, m, ',', r, c);
Kindly, what's wrong with this?
This answer was to answer OP's original error from using:
csvwrite(string('myMatrix'),L);
Error using csvwrite (line 30)
FILENAME must be a character vector.
The error you're seeing is an issue with your input (arguments). It's telling you that the file name must be a "character vector".
According to Matlab's documentation:
There are two ways to represent text in MATLABĀ®. Starting in R2016b, you can store text in string arrays. And in any version of MATLAB, you can store text in character arrays. A typical use for character arrays is to store pieces of text as character vectors. MATLAB displays strings with double quotes and character vectors with single quotes.
http://mathworks.com/help/matlab/matlab_prog/creating-character-arrays.html#briuv_1-1
In simple words. The wrong type was being used as an argument.
To provide a hint for debugging the new error.
Limitations
csvwrite writes a maximum of five significant digits. If you need greater precision, use dlmwrite with a precision argument.
csvwrite does not accept cell arrays for the input matrix M. To export a cell array that contains only numeric data, use cell2mat to convert the cell array to a numeric matrix before calling csvwrite.
http://mathworks.com/help/matlab/ref/csvwrite.html?requestedDomain=www.mathworks.com
Try checking what's in L. whos('L') would also help you get more info on it. An easy way to view what's in your variables, is double click from the workspace. Another way is by creating a break point on your call to csvwrite within a script, then use the debugger and calling for L once you know it's loaded into memory. If you still don't know what's going on, then try 'step in' line by line.
csvwrite does not accept cell arrays.

Import csv files in MATLAB

I'm trying to import a csv file (7816 x 119) with a lot of tiny numbers (between 1.0E-11 and 1.0E-9) using the following code:
filename = 'dataset.csv';
D = importdata(filename,',',1);
When I check the import result I obtain
D=
data: [187x119 double]
textdata: {1x119 cell}
colheaders: {1x119 cell}
Note that the size of D is a lot smaller than the original data size.
When I do the same process with a matrix with bigger numbers (not scientific notation) I don't have any problem.
I'm wondering if MATLAB have a restriction of size that I can import in a csv file or restrictions with numbers in scientific notation?
As is suspected, your data is corrupted in some places. Search for 'DIV' in the file, you will find an entry '#DIV/0!' several times. Interestingly, this worked in some matlab version for me (i currently don't know the version number) as well as it works in octave with a current release.
Here the test:
D = csvread('data_matlab.csv', 1, 0);
gives
Error using dlmread (line 143)
Mismatch between file and format string.
Trouble reading 'Numeric' field from file (row number 187, field number 72) ==>
#DIV/0!,1.11E-08,0,9.28E-09,2.8E-09,0.000000031,1.99E-08,6.49E-10,1.75E-09,9.66E-09,8.47E-10,3.82E-09,2.41E-10,1.71E-09,5.48E-09,1.32E-09,8.73E-09,2.05E-09,8.89E-10,3.83E-10,0,1.36E-08,2.92E-09,3.08E-...
Error in csvread (line 47)
m=dlmread(filename, ',', r, c);
Where do you get the data from? Can you influence the output? If you can't replace the errorneous entries by hand (using an appropriate tool) or use #Trogdors answer.
I was able to replicate the problem. Using xlsread did not produce that issue:
filename = 'data_matlab.csv';
d = xlsread(filename);

MATLAB: Undefined function 'libsvmwrite' for input arguments of type 'char'

I'm trying to convert a CSV file to LIBSVM/SVMlight format. I found the following code to do it:
SPECTF = csvread('SPECTF.train'); % read a csv file
labels = SPECTF(:, 1); % labels from the 1st column
features = SPECTF(:, 2:end);
features_sparse = sparse(features); % features must be in a sparse matrix
libsvmwrite('SPECTFlibsvm.train', labels, features_sparse);
I used it on Octave on a specific file, and it worked properly.
However, when trying it on MATLAB, I received the error:
Undefined function 'libsvmwrite' for input arguments of type 'char'.
Neither "labels" nor "features_sparse" are chars... (they are doubles). Where is my error? Thanks!
The first argument for libsvmwrite is of type char ( the filename 'SPECTFlibsvm.train'). I think the problem is on the error message given by Matlab. The error message says that the function doesn't exist for input of type char, but most likely it should be that it doesn't exist at all (the message could maybe make sense if Matlab was designed as an OPP language).
Anyway, you simply don't have the libsvmwrite function in your path, or you somehow messed up the installation of the libsvm interface.
Probably you loaded only the source code, which is written in c. You need to compile it. Go to the matlab directory of libsvm and read the instructions.

Error "Index exceeds matrix dimensions." in MatLab using importdata with a text file

I'm trying to import data using importdata and when I try to parse the returned data to create a matrix I get, "Index exceeds matrix dimensions". Below is my code...
traindata = importdata('textfile.txt');
%[A,delimiterOut,headerlinesOut] = importdata('textfile.txts');
disp(traindata); %everytime I run this code traindata increments by 1
X = traindata(' ',1:8); %this is where the error occurs, delimiter is 3 spaces
Y = traindata(' ',9);
Below is the format of the data in textfile.txt...
,,,5.4,,,0.0,,,0.0,,,1.6,,,2.5,,,1.0,,,6.7,,,2.8,,,6.1
,,,4.2,,,1.1,,,3.6,,,3.9,,,1.8,,,9.3,,,3.3,,,2.4,,,7.6
The data is delimited by spaces (I used commas to try and show the spaces between the data) and a newline at the end of each line. I've open textfile.txt in word and verified by viewing the hidden formatting characters. I've tried the code...
[A,delimiterOut,headerlinesOut] = importdata(inputfile);
to try to verify the delimiter used and I get the error, "Too many output arguments." As you can see I'm trying to create two matrices (X,Y) from the imported data. I've seen this specific error on stackoverflow but nothing regarding importdata. I've also tried dlmread and have not had luck. Thanks in advance for any help.
Tried the suggestion of importing the data using file->import data but I receive the error..
Error using importdata
Too many output arguments.
"Error in uiimport/runImportdata (line 433)
[datastruct, OTextDelimiter, OHeaderLines] = ...
Error in uiimport/gatherFilePreviewData (line 376)
[datastruct, textDelimiter, headerLines]= runImportdata(fileAbsolutePath, type);
Error in uiimport (line 194)
[ctorPreviewText, ctorHeaderLines, ctorDelim] = ..."
I'm starting to wondering if it's some sort of application bug. Here are some specifics..
"R2012a (7.0.14.739) 64 bit (Win64)". The encoding of the text file is utf-8. Thanks again for the help!
Looks like the array returned from importdata is a 1 element array.
train = importdata('textfile.txt');
fprintf('1st element in array %d\n', traindata(1)); % prints a number a number that increase each time I run this function ie 1,2,3,4...
fprintf('2nd element in array %d\n', traindata(2)); % produces error, "Index exceeds matrix dimensions"
I often find it useful to use matlab's built in GUI for importing a data file, which can help to visualised how the data will be imported. There is an option in here to produce the code required to replicate the options that were selected during the import which will allow you to work out how to dynamically import the data.
Just go to:
File >>> Import Data...