Issue when writing matrix to file using csvwrite - matlab

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.

Related

Matlab string concatenation behavior with different data types

I am using Matlab 2018b on Windows 10. I understand that the Matlab string concatenation needs input arguments under concatenation to be a character array, a cell array of character vectors, or a string array as mentioned in https://de.mathworks.com/help/matlab/ref/strcat.html. Based on this i was expecting an error while trying to do the following:
[1, 'some_string']
or
strcat(1, 'some_string')
But i am not getting any error message. Instead getting output as displayed in the snapshot below:
Based on below, looks like automatic type conversion is taking place for 1 from double to char but seems something in getting wrong in the process resulting in 1 being replaced with a junk char. Any insight in to this please?
x = strcat(1, 'some_string');
class(x(1))
ans =
'char'
Matlab is treating the 1 as an ascii code, corresponding to the start of heading character which is being displayed as the square you see.
It is more obvious what Matlab is doing if you e.g. do strcat(65, 'some_string'), which returns Asome_string as the ascii code 65 corresponds to a capital A.

MATLAB: Error in array2table

I'm not able resolve this error i face when running MATLAB's array2table function
The VariableNames property must be a cell array, with each element
containing one nonempty character vector.
array2table([1,2,3],'VariableNames',{"str1", "str2", "str3"})
I had a read at MATLAB's array2table documentation and my syntax mimick's MATLAB's give examples, hence i can't figure out where i went wrong. Would appreciate some help.
Rephrasing the error message: String and character arrays are different things. You're using cells of strings but the function expects you to use cells of characters. i.e.
array2table([1,2,3],'VariableNames',{'str1', 'str2', 'str3'})
Relevant documentation for further understanding: Characters and Strings

Can i write out a txt or csv doc with data of varying dimensions in Matlab?

I am using Matlab R2013b.
I have a 100x100 matrix which contains both numbers and strings. I converted it to a cell array (alldat) and wrote it to a csv file (blah.csv).
I then tried to append a single number to the top line of this csv file...which Matlab won't let me do.
cell2csv('blah.csv',alldat)
I can append the single number 'n' at the bottom of the matrix:
dlmwrite('blah.csv',n,'-append','delimiter',' ','roffset',1)
But it won't let me do it the other way around (so I can put the number in the first cell of the csv file, then have the matrix below it.
Can anyone advise?
I also tried outputting the cell array to a txt document using dlmwrite:
dlmwrite('blah.txt',alldat,'delimiter',' ');
And I kept getting this error:
Error using dlmwrite (line 113) The input cell array cannot be
converted to a matrix.
I often use tables for such tasks. Since you have a 100 x 100 array and not variables with different dimensions, it should be possible to adapt.
VarA={'12A3';123;'12B3'};
VarB={'45A6';456;'45B6'};
T=table(VarA,VarB);
writetable(T,'test.csv','WriteVariableNames',false)
T1=readtable('test.csv','ReadVariableNames',false)
You may want to use cell2table to create a table directly from your cell array, although it didn't work for me because it made some strange conversions from number to character.

Error encoding with Huffman in Matlab

I have a file where i can read the next example of characters:
HP†d€H EPŠ€E iEPƒ1€E OGP†d€G HP†d€H JP†d€J LP†d€L.......
And when I try to encode the samples of the file using the function of Matlab "huffmanenco" Matlab says me this:
Error using huffmanenco (line 86)
The Huffman dictionary provided does not have the codes for all the input
signals.
Error in RETO2 (line 35)
enco=huffmanenco(double(x),dict);
The next code is the one I'm using:
fileID = fopen('reto2014.mid');
[x,cont]=fscanf(fileID,'%c');
fclose(fileID);
y=[1:256];
va = hist(double(x),y);
prob= va./cont;
bar(y,prob)
[dict,avglen]=huffmandict(y,prob);
enco=huffmanenco(double(x),dict);
I have tried to change the variable "y" but that doesn't work or it says me that The Maximum recursion limit of 500 have been reached what can I do to fix it?
You create a dictionary for the values 1 to 256, but your text has characters with larger number representations. Using the characters you posted, you find that the minimum is 32 and the maximum is 8364. You have to create a dictionary containing all possible characters:
y = double(unique(x));
This should give the desired results. You could also use
y = 1:65535;
which will probably give you exactly the same result, as for all characters which you don't have in your text x, the probability is 0.

MATLAB uint8 data type variable save

does anyone know how to save an uint8 workspace variable to a txt file?
I tried using MATLAB save command:
save zipped.txt zipped -ascii
However, the command window displayed warning error:
Warning: Attempt to write an unsupported data type to an ASCII file.
Variable 'zipped' not written to file.
In order to write it, simply cast your values to double before writing it.
A=uint8([1 2 3])
toWrite=double(A)
save('test.txt','toWrite','-ASCII')
The reason uint8 can't be written is hidden in the format section of the save doc online, took myself a bit to find it.
The doc page is here: http://www.mathworks.com/help/matlab/ref/save.html
The 3rd line after the table in the format section (about halfway down the page) says:
Each variable must be a two-dimensional double or character array.
Alternatively, dlmwrite can write matrices of type uint8, as the other poster also mentioned, and I am sure the csv one will work too, but I haven't tested it myself.
Hopefully that will help you out, kinda annoying though! I think uint8 is used almost exclusively for images in MATLAB, but I am assuming writing the values as an image is not feasible in your situation.
have you considered other write-to-file options in Matlab?
How about dlmwrite?
Another option might be cvswrite.
For more information see this document.
Try the following:
%# a random matrix of type uint8
x = randi(255, [100,3], 'uint8');
%# build format string
frmt = repmat('%u,',1,size(x,2));
frmt = [frmt(1:end-1) '\n'];
%# write matrix to file in one go
f = fopen('out.txt','wt');
fprintf(f, frmt, x');
fclose(f);
The resulting file will be something like:
16,108,149
174,25,138
11,153,222
19,121,68
...
where each line corresponds to a matrix row.
Note that this is much faster than using dlmwrite which writes one row at a time