I have a cell array. I want to write each element of the cell into a .csv file and also specifically name the file along the way.
This is my attempt:
for i=1:length(somecell)
doublecell{i}=double(somecell{i});
end
for j=1:length(doublecell)
z=doublecell{j};
csvwrite('matrix_%i.csv',z,j)
end
I hope what I'm attempting to do is clear even though it's wrong.
You can shorten (and correct) your code as:
for i = 1:length(somecell)
doubleVal = double(somecell{i});
csvwrite(sprintf('matrix_%i.csv', i), doubleVal);
end
You don't have to store the double values in an intermediate cell array, as you can produce the elements while you write the CSV files.
There were actually two problems with your code:
The line z=doublecell(j) produces a cell as indexing a cell-array with parenthesis produces a cell. You would need the numeric value instead, so here the curly bracket indexing would be correct: z = doublecell{j}.
The line csvwrite('matrix_%i.csv',z,j) is incorrect. You would need sprintf to create the filename (see example).
Related
I'm writing a code to import data from a CSV file and convert it into an Octave matrix. The imported data can be seen in the following snap:
In the next step I added the following command to delete the commas and "":
meas_raw_temp = strrep(meas_raw_temp,',',' ')
And then I get the data format in the following form:
The problem is that Octave still sees the data as 1 single 1-dimensional array. i.e., when I use the size command I get a single number, i.e. 2647. What I need to have is a matrix output, with each line of the snaps being a row of the matrix, and with each element separated.
Any thoughts?
Here's what's happening.
You have a 1-dimensional (rows only) cell array. Each element (i.e. cell) in the cell array contains a single string.
Your strings contain commas and literal double-quotes in them. You have managed to get rid of them all by replacing them in-place with an 'empty string'. Good. However that doesn't change the fact that you still have a single string per cell.
You need to create a for loop to process each cell separately. For each cell, split the string into its components (i.e. 'tokens') using ' ' (i.e. space) as the delimiter. You can use either strsplit or strtok appropriately to achieve this. Note that the 'tokens' you get out of this process are still of 'string' type. If you want numbers, you'll need to convert them (e.g. using str2double or something equivalent).
For each cell you process, find a way to fill the corresponding row of a preallocated matrix.
As Adriaan has pointed out in the comments, the exact manner in which you follow the steps above programmatically can vary, therefore I'm not going to provide the range of possible ways that you could do so, and I'm limiting the answer to this question to the steps above, which is how you should think about solving your problem.
If you attempt these steps and get stuck on a 'programmatic' aspect of your implementation, feel free to ask another stackoverflow question.
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.
Trying to join different files with an specific suffix in a matrix, but always I obtain a matrix with unique row containing the values of the last file..
As example
I have multiple files like:
2302_Cabeza_L_x.txt, 2202_Cabeza_L_x.txt, 1702_Cabeza_L_y.txt.....
The code I'm using...
codes= [2302,2202,1602,1502,1702];
for p=1:length(codes)
name=mat2str(codes(:,p));
orden2=(name(2:length(name)-11));
orden=str2num(orden2);
allCABLX = importdata([name '_Cabeza_L_x.txt']);
allCABLY = importdata([name '_Cabeza_L_y.txt']);
allCABCY = importdata([name '_Cabeza_C_y.txt']);
allCABCX = importdata([name '_Cabeza_C_x.txt']);
end
Thank you!
You are overwriting the variables allCABLX, allCABLY, allCABCY and allCABCX in every iteration, so only the last values stay there after the loop. You need to save the data inside the loop to be able to access it afterwards.
If all files have the same number of entries, this can be achieved by concatenating the values obtained by importdata. Since I don't know the dimensions of the output of importdata, I'm not going into the details here.
If the files have different number of entries, you can use a cell array to store the data of each iteration. This works as well in case all entries are of the same size. The following code does exactly this for one of the variables:
codes= [2302,2202,1602,1502,1702];
allCABLX = cell(length(codes),1); % create empty cell array
for p=1:length(codes)
name=num2str(codes(:,p));
allCABLX{p} = importdata([name '_Cabeza_L_x.txt']);
end
Note that I replaced mat2str by num2str since you only have a number to convert and not a whole matrix. In case all the files have data of the same dimension, you can use cell2mat after the loop to get a normal matrix.
I've made a cell array that goes through the names of 50 text files I need to analyze. However, when referencing a particular character element as the title for textread, I get an error.
Example:
NameCell = {'file1.txt' 'file2.txt'};
vec = textread(NameCell{1},'%n','headerlines',23);
If I input the actual file name ('file1.txt') into the textread function, I get the vector I want, but it can't reference from the cell. Is there a way around this?
Thank you!
If I have a Matlab CELL line of string characters separated by a comma like:
12/28/2012,00:00:01,0.99458,1,10518,0.99458,0.99483,0,0,0,0,-,-,-,b,-,C
How do I separate each one into its own column within a matrix? What is the most efficient way of doing this?
Can this be done?
Thanks
UPDATE: Just realized this question duplicates how-to-convert-comma-separated-string-to-cell-array-of-strings-in-matlab and that my answer duplicates the answer provided by #Jonas. I'm flagging it as a duplicate.
Here is the most efficient method I'm aware of:
%# Build your string
Input = '12/28/2012,00:00:01,0.99458,1,10518,0.99458,0.99483,0,0,0,0,-,-,-,b,-,C';
%# Convert to cell array of strings
Output = regexp(Input, '([^,]*)', 'tokens');
Output = cat(2, Output{:});
Some points to note:
1) Note, this will work whether Input is a character array (ie a string) or a cell containing a character array.
2) I've assumed you want the output to be a cell array of strings. Offhand, I can't think of another way of grouping strings of differing length into separate columns using Matlab without building your own custom class.
3) The solution provided by #IlyaKobelevskiy will group the strings into separate rows (not columns) and thus essentially limits you to only a single observation.
Assuming str is your cell line:
str ={'12/28/2012,00:00:01,0.99458,1,10518,0.99458,0.99483,0,0,0,0,-,-,-,b,-,C'};
ind=strfind(str{1},',');
len=diff([0 ind]);
sz=max(len);
A=zeros(length(ind),sz);
prev=1;
for i=1:length(ind)
A(i,1:len(i)-1)=str{1}(prev:(ind(i)-1));
prev=ind(i)+1;
end;
A=char(A);
Not sure if it is the most efficient way, but should work...