How to Separate Commas and save the values in a Matrix Array. - arrays

I have the following dataset and i want to separate the txt values and commas and save to a 10x18 matrix.
I tried with str2mat(char(txt(...)) but it didn't help. It separates the value and make individual character. How can I save the data in matrix.
'1,4,5,12,13,17,22,24,25,21,20,17,12,12,10,9,8,4'
'2,4,6,7,9,10,13,15,17,17,14,13,12,11,9,7,5,2'
'3,7,8,10,11,13,14,15,18,18,16,15,14,11,10,5,4,2'
'5,5,8,9,15,17,18,20,21,22,21,17,15,14,12,11,6,2'
'5,6,8,10,14,15,19,21,24,19,17,16,14,13,10,5,3,2'
'4,6,7,9,10,13,17,19,20,20,19,17,16,12,11,9,7,1'
'6,7,12,16,19,20,21,22,24,24,22,17,9,6,4,3,2,1'
'4,8,10,11,14,16,18,22,24,22,21,19,18,13,8,6,5,4'
'1,3,11,12,14,15,17,18,22,21,20,16,15,14,11,7,6,2'
'2,5,11,15,18,19,22,26,27,25,22,17,9,8,7,4,2,1'

As simple as:
text = '1,2,3':
nums = strsplit(text,',');
vals = str2double(nums);

Related

Matlab: Export concatenation of cell arrays into a txt file

I have two different sets of arrays within an array, which I called:
y={...}; % cell array of 1x1, with a 26x1 cell array within it.
Only_Data={...} %cell array of 525x1, with 525 different 1x12 cell arrays
The data that's within the arrays is string. I want to concatenate these two arrays into one and print that final result into a .txt file. But I'm having problems doing the last part.
This is what I've done for that purpuse:
new_subject3=[y; Only_Data];
new_subject3;
outfile='mynewfile';
filename=[outfile,'.txt'];
fid=fopen(filename,'w');
[nrows,ncols] = size(new_subject3);
for row = 1:nrows
fprintf(fid ,'%s\n', new_subject3{row}{1:end});
end
fclose(fid);
For some reason I'm not aware of, it only prints the 'y' array, but doesn't print anything from the 'Only_Data' array. Why would that be? I'm clueless. I'm sure it's not about the type of data, but further than that I don't know.
I'll be glad to learn how to do this, thanks in advance.

Add string to 1-D cell array without determing its length in MATLAB

I have some strings in file.txt and I want to add all of it to a cell array.
But the problem is a number of strings in file are unknown and I don't want to count. I want each time I read 1 string in file (from top to bottom), I'll add it to cell array.
Example:
**file.txt**
ABC
DEFG
HI
JKLMNO
--> cellarray(1) = 'ABC', cellarray(2) = 'DEFG', cellarray(3) = 'HI', cellarray(4) = 'JKLMNO'
I'm using MATLAB R2014b. How can I do this?
You can use textscan to load your entire file into a cell array of strings. The result is going to be a 1 x 1 cell array because you only have one format specifier (%s) but that cell array will contain another cell array of all of the lines in the file.
fid = fopen('file.txt', 'rt');
data = textscan(fid, '%s', 'delimiter', '\r\n');
C = data{1};
%// 'ABC'
%// 'DEFG'
%// 'HI'
%// 'JKLMNO'
You can get a line from text file using the fgets function in MATLAB (Documentation)

Cell array to matrix conversion in matlab

I would like to covert three <1xN cell> (A, B and C) into a single Nx3 matrix. Could someone help me with this?
C={{1xN}; {1xN}; {1xN}};
where each N is a number in single quotes, e.g.
C = {{'123123' ,'12324', ....N times}; {'123123', '12324', ....N times}; {'123123', '12324' ,....N times}}
Since a couple of them mentioned about the ridiculous input, this is the reason for having it in the above form.
The three nested array of cells are the results of a regexp where my string and expression are both strings. Therefore I have the output of regexp as three cell arrays of row vectors.
For e.g.
node_ids=regexp(nodes,'(?<=node id=")\d*','match');
I can use cat function and then use a str2double for all three cell arrays and finally form a matrix by cell2mat.
For e.g.
node_ids=cat(1,node_ids{:});node_ids=str2double(node_ids);
But this takes more time and has more LOC.
My question is can it be done with fewer lines of code?
I tried using the cat function but keep getting this error:
Cannot support cell arrays containing cell arrays or objects.
Your input data is pretty bad.... why are you using a nested array of cells where each element is a string?
In any case, assuming C is your original input data, do this:
C = {{'123123' '12324'}; {'123123' '12324'}; {'123123' '12324'}};
out = cellfun(#(x) cellfun(#str2num, x, 'uni', 0), C, 'uni', 0);
out = cell2mat(cellfun(#cell2mat, out, 'uni', 0));
First line is some dummy data. Next line first goes through every nested cell element over your cell array and converts the strings into numbers. However, these are still in cell arrays. As such, the next line converts each cell array in the nested cell into a matrix, then we merge all of the cells together into one final matrix.
We get:
>> out
out =
123123 12324
123123 12324
123123 12324

Apply a string value to several positions of a cell array

I am trying to create a string array which will be fed with string values read from a text file this way:
labels = textread(file_name, '%s');
Basically, for each string in each line of the text file file_name I want to put this string in 10 positions of a final string array, which will be later saved in another text file.
What I do in my code is, for each string in file_name I put this string in 10 positions of a temporary cell array and then concatenate this array with a final array this way:
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector{1:10}=labels{i};
final_vector=horzcat(final_vector,temp_vector);
end
But when I run the code the following error appears:
The right hand side of this assignment has too few values to satisfy the left hand side.
Error in my_example_code (line 16)
temp_vector{1:10}=labels{i};
I am too rookie in cell strings in matlab and I don't really know what is happening. Do you know what is happening or even have a better solution to my problem?
Use deal and put the left hand side in square brackets:
labels{1} = 'Hello World!'
temp_vector = cell(10,1)
[temp_vector{1:10}] = deal(labels{1});
This works because deal can distribute one value to multiple outputs [a,b,c,...]. temp_vector{1:10} alone creates a comma-separated list and putting them into [] creates the output array [temp_vector{1}, temp_vector{2}, ...] which can then be populated by deal.
It is happening because you want to distribute one value to 10 cells - but Matlab is expecting that you like to assign 10 values to 10 cells. So an alternative approach, maybe more logic, but slower, would be:
n = 10;
temp_vector(1:n) = repmat(labels(1),n,1);
I also found another solution
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector(:,1:10)=cellstr(labels{i});
final_vector=horzcat(final_vector,temp_vector);
end

How to save a structure array to a text file

In MATLAB how do I save a structure array to a text file so that it displays everything the structure array shows in the command window?
I know this thread is old but I hope it's still going to help someone:
I think this is an shorter solution (with the constraint that each struct field can contain scalar,arrays or strings):
%assume that your struct array is named data
temp_table = struct2table(data);
writetable(temp_table,'data.csv')
Now your struct array is stored in the data.csv file. The column names are the field names of a struct and the rows are the different single-structs of your struct-array
You have to define a format for your file first.
Saving to a MATLAB workspace file (.MAT)
If you don't care about the format, and simply want to be able to load the data at a later time, use save, for example:
save 'myfile.mat' structarr
That stores struct array structarr in a binary MAT file named "file.mat". To read it back into your workspace you can use load:
load 'myfile.mat'
Saving as comma-separated values (.CSV)
If you want to save your struct array in a text file as comma-separated value pairs, where each pair contains the field name and its value, you can something along these lines:
%// Extract field data
fields = repmat(fieldnames(structarr), numel(structarr), 1);
values = struct2cell(structarr);
%// Convert all numerical values to strings
idx = cellfun(#isnumeric, values);
values(idx) = cellfun(#num2str, values(idx), 'UniformOutput', 0);
%// Combine field names and values in the same array
C = {fields{:}; values{:}};
%// Write fields to CSV file
fid = fopen('myfile.csv', 'wt');
fmt_str = repmat('%s,', 1, size(C, 2));
fprintf(fid, [fmt_str(1:end - 1), '\n'], C{:});
fclose(fid);
This solution assumes that each field contains a scalar value or a string, but you can extend it as you see fit, of course.
To convert any data type to a character vector as displayed in the MATLAB command window, use the function
str = matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(yourArray);
You can then write the contents to a file
fid = fopen('myFile.txt', 'w');
fwrite(fid, str, '*char');
fclose(fid);

Resources