Create an array of strings - matlab

Is it possibe to create an array of strings in MATLAB within a for loop?
For example,
for i=1:10
Names(i)='Sample Text';
end
I don't seem to be able to do it this way.

You need to use cell-arrays:
names = cell(10,1);
for i=1:10
names{i} = ['Sample Text ' num2str(i)];
end

You can create a character array that does this via a loop:
>> for i=1:10
Names(i,:)='Sample Text';
end
>> Names
Names =
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
However, this would be better implemented using REPMAT:
>> Names = repmat('Sample Text', 10, 1)
Names =
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

Another option:
names = repmat({'Sample Text'}, 10, 1)

New features have been added to MATLAB recently:
String arrays were introduced in R2016b (as Budo and gnovice already mentioned):
String arrays store pieces of text and provide a set of functions for
working with text as data. You can index into, reshape, and
concatenate strings arrays just as you can with arrays of any other
type.
In addition, starting in R2017a, you can create a string using double quotes "".
Therefore if your MATLAB version is >= R2017a, the following will do:
for i = 1:3
Names(i) = "Sample Text";
end
Check the output:
>> Names
Names =
1×3 string array
"Sample Text" "Sample Text" "Sample Text"
No need to deal with cell arrays anymore.

Another solution to this old question is the new container string array, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:
a=repmat('Some text', 10, 1);
This solution resembles a Rich C's solution applied to string array.

As already mentioned by Amro, the most concise way to do this is using cell arrays. However, Budo touched on the new string class introduced in version R2016b of MATLAB. Using this new object, you can very easily create an array of strings in a loop as follows:
for i = 1:10
Names(i) = string('Sample Text');
end

one of the simplest ways to create a string matrix is as follow :
x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

Related

Saving figure without providing filename [duplicate]

this question about matlab:
i'm running a loop and each iteration a new set of data is produced, and I want it to be saved in a new file each time. I also overwrite old files by changing the name. Looks like this:
name_each_iter = strrep(some_source,'.string.mat','string_new.(j).mat')
and what I#m struggling here is the iteration so that I obtain files:
...string_new.1.mat
...string_new.2.mat
etc.
I was trying with various combination of () [] {} as well as 'string_new.'j'.mat' (which gave syntax error)
How can it be done?
Strings are just vectors of characters. So if you want to iteratively create filenames here's an example of how you would do it:
for j = 1:10,
filename = ['string_new.' num2str(j) '.mat'];
disp(filename)
end
The above code will create the following output:
string_new.1.mat
string_new.2.mat
string_new.3.mat
string_new.4.mat
string_new.5.mat
string_new.6.mat
string_new.7.mat
string_new.8.mat
string_new.9.mat
string_new.10.mat
You could also generate all file names in advance using NUM2STR:
>> filenames = cellstr(num2str((1:10)','string_new.%02d.mat'))
filenames =
'string_new.01.mat'
'string_new.02.mat'
'string_new.03.mat'
'string_new.04.mat'
'string_new.05.mat'
'string_new.06.mat'
'string_new.07.mat'
'string_new.08.mat'
'string_new.09.mat'
'string_new.10.mat'
Now access the cell array contents as filenames{i} in each iteration
sprintf is very useful for this:
for ii=5:12
filename = sprintf('data_%02d.mat',ii)
end
this assigns the following strings to filename:
data_05.mat
data_06.mat
data_07.mat
data_08.mat
data_09.mat
data_10.mat
data_11.mat
data_12.mat
notice the zero padding. sprintf in general is useful if you want parameterized formatted strings.
For creating a name based of an already existing file, you can use regexp to detect the '_new.(number).mat' and change the string depending on what regexp finds:
original_filename = 'data.string.mat';
im = regexp(original_filename,'_new.\d+.mat')
if isempty(im) % original file, no _new.(j) detected
newname = [original_filename(1:end-4) '_new.1.mat'];
else
num = str2double(original_filename(im(end)+5:end-4));
newname = sprintf('%s_new.%d.mat',original_filename(1:im(end)-1),num+1);
end
This does exactly that, and produces:
data.string_new.1.mat
data.string_new.2.mat
data.string_new.3.mat
...
data.string_new.9.mat
data.string_new.10.mat
data.string_new.11.mat
when iterating the above function, starting with 'data.string.mat'

Insert String in a CSV file matlab

how do I insert a string into a csv file in matlab. i used this code to write some data and create my csv file:
and here is the output of the code:
I'm trying to insert some text in the first 2 columns before the numerical data..
thanks in advance :)
There are several approaches are possible here.
Let's take a look at some of them:
If you need to add string to your csv file.
For example, I create some csv file like your:
q = [1 2 3 4 5 6 7];
csvwrite('csvlist4.csv',q,2,0);
All troubles is to add some string to csv - it's because we need to combine numeric and text data. There are no good functions for it in Matlab except low levels:
c = 'some big text';
fid = fopen('csvlist4.csv','r+');
fprintf(fid,c);
How it works: the data in csv is an array. I put data in 3rd row, so first and second is an empty but they have ','. When you use fprintf it will replace this , with your text. So if text is too long it will overwrite your data.
How to avoid this?
Easiest way - is to do it with help of xlswrite function. For your example:
txt = cell(size(Q))
txt{1} = 'this is your text'
X = [txt; num2cell(Q)]
xlswrite('new.xlsx',X)
Result:
Important moment here: number of cell for text must be the same as your data. But I filled with the text only first cell in my example.
And the one more way: read csv file, modify it's data and write to csv:
csvwrite('csvlist4.csv',a,2,0);
m = csvread('csvlist4.csv');
fid = fopen('csvlist4.csv','w');
c = 'your text'
fprintf(fid, c); fprintf(fid, '\n');
fclose(fid);
dlmwrite('csvlist4.csv', m(3:end,:), '-append');
Of course you can use cell array instead c and so on and so on.
Hope it helps!

Using fscanf in MATLAB to read an unknown number of columns

I want to use fscanf for reading a text file containing 4 rows with an unknown number of columns. The newline is represented by two consecutive spaces.
It was suggested that I pass : as the sizeA parameter but it doesn't work.
How can I read in my data?
update: The file format is
String1 String2 String3
10 20 30
a b c
1 2 3
I have to fill 4 arrays, one for each row.
See if this will work for your application.
fid1=fopen('test.txt');
i=1;
check=0;
while check~=1
str=fscanf(fid1,'%s',1);
if strcmp(str,'')~=1;
string(i)={str};
end
i=i+1;
check=strcmp(str,'');
end
fclose(fid1);
X=reshape(string,[],4);
ar1=X(:,1)
ar2=X(:,2)
ar3=X(:,3)
ar4=X(:,4)
Once you have 'ar1','ar2','ar3','ar4' you can parse them however you want.
I have found a solution, i don't know if it is the only one but it works fine:
A=fscanf(fid,'%[^\n] *\n')
B=sscanf(A,'%c ')
Z=fscanf(fid,'%[^\n] *\n')
C=sscanf(Z,'%d')
....
You could use
rawText = getl(fid);
lines = regexp(thisLine,' ','split);
tokens = {};
for ix = 1:numel(lines)
tokens{end+1} = regexp(lines{ix},' ','split'};
end
This will give you a cell array of strings having the row and column shape or your original data.
To read an arbitrary line of text then break it up according the the formating information you have available. My example uses a single space character.
This uses regular expressions to define the separator. Regular expressions powerful but too complex to describe here. See the MATLAB help for regexp and regular expressions.

Writing columns of data into a text file

I'm using the following code to write the vectors sortedthresh_strain and probofdetectionanddelamprop1 into a text file. However, the text file output is as follows:
0.0030672 1.6592e-080.0033489 5.1721e-080.0034143
where 0.0033489 5.1721e-08 should be on the next line of the text file. i.e. It should be:
0.0030672 1.6592e-08
0.0033489 5.1721e-08
I am unsure of how to do this.
Edit: Using the proposed answer:
0.0049331 0.0049685 0.0049894 0.0050094 0.005156 0.0051741 0.0052139 0.0053399 0.0054486 0.0056022 7.0711e-21 3.0123e-19
The 2nd column is required to contain:
7.0711e-21
3.0123e-19
And,
dlmwrite('THRESHUNCERTAINTYFINALPLOTLSIGMA5.dat'[sortedthresh_strain,probofdetectionanddelamprop1],'delimiter', '\t');
If you have R2013b or later, see this answer. If you have an earlier version but have the statistics toolbox you can use the dataset object to do this very easily just like tables in R2013b. Using dataset:
data1 = {'a','b','c'}'
data2 = [1, 2, 3]'
ds = dataset(data1, data2)
export(ds, 'file', 'data.txt')
If you don't want the variable names in the result text file you can use 'WriteVarNames', false in your call to export.
Good luck!
I think your data is in row vectors, but should be column vectors for it to work like you want.
Just add a transpose with '.
dlmwrite('THRESHUNCERTAINTYFINALPLOTLSIGMA5.dat',[sortedthresh_strain',probofdetectionanddelamprop1'],'delimiter', '\t');

printing a vector of string in static text box with new lines

I have a bunch of classes that I am iterating through and collecting which classes the student is failing in. If the student fails , I collect the name of the class in a vector called retake.
retake =[Math History Science]
I have line breaks so when the classes print in the command window it shows as:
retake=
Math
History
Science.
However, I am trying display retake in a static text box in Gui Guide so it looks like the above. Instead, the static text box is showing as:
MathHistoryScience
set(handles.text13,'String', retake) % this is what I tried
can you please show me so it prints:
Math
History
Science
It looks to me like you need to add carriage returns.
Assuming you have a cell array with strings (rather than concatenated strings using [], which will give you a single long line), you can do it as follows:
retake = {'Math', 'History', 'Science'};
rString = '';
for ii = 1:numel(retake)-1
rString = [rString sprintf('%s\n', retake{ii}];
end
rString = [rString retake{end}];
Notice the use of '' to denote strings, {} to denote a cell array, '\n' as the end-of-line character, and [a b] to do simple string concatenation.