cell array, add suffix to every string - string

Suppose I have a cell array containing strings:
c = {'foo1', 'foo2', 'foo3'}
I now want to add the same suffix "bar" to each string, such that the cell array becomes:
c = {'foo1bar', 'foo2bar', 'foo3bar'}
Is there a shortcut to doing this, without explicitly looping through each element?

strcat operates on cell arrays:
>> c = {'foo1', 'foo2', 'foo3'}
c =
'foo1' 'foo2' 'foo3'
>> c2 = strcat(c,'bar')
c2 =
'foo1bar' 'foo2bar' 'foo3bar'

What about using cellfun:
c=cellfun(#(x) strcat(x, 'bar'), c, 'Uniformoutput', 0);
I don't know if it's faster to run than a loop, but it's less tedious to write.
Edit: apparently strcat handles cell arrays. Use cellfun for functions that don't.

Related

Finding indexes of strings in a string array in Matlab

I have two string arrays and I want to find where each string from the first array is in the second array, so i tried this:
for i = 1:length(array1);
cmp(i) = strfind(array2,array1(i,:));
end
This doesn't seem to work and I get an error: "must be one row".
Just for the sake of completeness, an array of strings is nothing but a char matrix. This can be quite restrictive because all of your strings must have the same number of elements. And that's what #neerad29 solution is all about.
However, instead of an array of strings you might want to consider a cell array of strings, in which every string can be arbitrarily long. I will report the very same #neerad29 solution, but with cell arrays. The code will also look a little bit smarter:
a = {'abcd'; 'efgh'; 'ijkl'};
b = {'efgh'; 'abcd'; 'ijkl'};
pos=[];
for i=1:size(a,1)
AreStringFound=cellfun(#(x) strcmp(x,a(i,:)),b);
pos=[pos find(AreStringFound)];
end
But some additional words might be needed:
pos will contain the indices, 2 1 3 in our case, just like #neerad29 's solution
cellfun() is a function which applies a given function, the strcmp() in our case, to every cell of a given cell array. x will be the generic cell from array b which will be compared with a(i,:)
the cellfun() returns a boolean array (AreStringFound) with true in position j if a(i,:) is found in the j-th cell of b and the find() will indeed return the value of j, our proper index. This code is more robust and works also if a given string is found in more than one position in b.
strfind won't work, because it is used to find a string within another string, not within an array of strings. So, how about this:
a = ['abcd'; 'efgh'; 'ijkl'];
b = ['efgh'; 'abcd'; 'ijkl'];
cmp = zeros(1, size(a, 1));
for i = 1:size(a, 1)
for j = 1:size(b, 1)
if strcmp(a(i, :), b(j, :))
cmp(i) = j;
break;
end
end
end
cmp =
2 1 3

Matlab: trasform to cell of strings

Problem: I have postfix (137x25) cell that contain cell of char (Ex postfix(6,8)=postfix{6,8}{1,1}<1x3char>). I want to trasform it in (137x25) cell of char.
Postfix is created in this way:
for l=1:25
[matches(:,l), postfix(:,l)] = regexp(semanticTrajCompact(1,4).TrajCompact,sprintf('%d%d(.*)',digits{1}(l),digits{2}(l)),'match','once','tokens');
end
I have tried different solutions:
Solution 1
numIndex = cellfun('isclass', postfix, 'double');
tmpStr = sprintf('%g;', postfix{numIndex});
postfix(numIndex) = dataread('string', tmpStr, '%s', 'delimiter', ';');
Solution 2
postfix(cellfun(#isempty,postfix))={''};
Solution 3
postfix(cellfun(#isnumeric, postfix)) = cellfun(#(x) sprintf('%.5f', x), postfix(cellfun(#isnumeric, postfix)), 'UniformOutput', false)
Solution 4
I try to use
char(postix)
Anyone of this solution trasform postfix in a (137x25 array of char). Can you give me other ideas?
You want to loop over every element of the cell array postfix, and replace each element of the cell array (which is a cell array itself) by its contents. Using cellfun to replace the loop, you therefore write:
postfix = cellfun(#(x)x{1}, postfix, 'UniformOutput', false);
I have solved the problem also in this way
for k=1:25
for j=size(postfix,1)
if(~isempty(postfix{j,k}))
postfix{j,k}=char(postfix{j,k}{1,1});
end
end
end
postfix(cellfun(#isempty,postfix))={''};

Is it possible to concatenate a string with series of number?

I have a string (eg. 'STA') and I want to make a cell array that will be a concatenation of my sting with a numbers from 1 to X.
I want the code to do something like the fore loop here below:
for i = 1:Num
a = [{a} {strcat('STA',num2str(i))}]
end
I want the end results to be in the form of {<1xNum cell>}
a = 'STA1' 'STA2' 'STA3' ...
(I want to set this to a uitable in the ColumnFormat array)
ColumnFormat = {{a},... % 1
'numeric',... % 2
'numeric'}; % 3
I'm not sure about starting with STA1, but this should get you a list that starts with STA (from which I guess you could remove the first entry).
N = 5;
[X{1:N+1}] = deal('STA');
a = genvarname(X);
a = a(2:end);
You can do it with combination of NUM2STR (converts numbers to strings), CELLSTR (converts strings to cell array), STRTRIM (removes extra spaces)and STRCAT (combines with another string) functions.
You need (:) to make sure the numeric vector is column.
x = 1:Num;
a = strcat( 'STA', strtrim( cellstr( num2str(x(:)) ) ) );
As an alternative for matrix with more dimensions I have this helper function:
function c = num2cellstr(xx, varargin)
%Converts matrix of numeric data to cell array of strings
c = cellfun(#(x) num2str(x,varargin{:}), num2cell(xx), 'UniformOutput', false);
Try this:
N = 10;
a = cell(1,N);
for i = 1:N
a(i) = {['STA',num2str(i)]};
end

MATLAB empty cell(n,m) array of strings?

What is the quickest way to create an empty cell array of strings ?
cell(n,m)
creates an empty cell array of double.
How about a similar command but creating empty strings ?
Depends on what you want to achieve really. I guess the simplest method would be:
repmat({''},n,m);
Assignment to all cell elements using the colon operator will do the job:
m = 3; n = 5;
C = cell(m,n);
C(:) = {''}
The cell array created by cell(n,m) contains empty matrices, not doubles.
If you really need to pre populate your cell array with empty strings
test = cell(n,m);
test(:) = {''};
test(1,:) = {'1st row'};
test(:,1) = {'1st col'};
This is a super old post but I'd like to add an approach that might be working. I am not sure if it's working in an earlier version of MATLAB. I tried in 2018+ versions and it works.
Instead of using remat, it seems even more convenient and intuitive to start a cell string array like this:
C(1:10) = {''} % Array of empty char
And the same approach can be used to generate cell array with other data types
C(1:10) = {""} % Array of empty string
C(1:10) = {[]} % Array of empty double, same as cell(1,10)
But be careful with scalers
C(1:10) = {1} % an 1x10 cell with all values = {[1]}
C(1:10) = 1 % !!!Error
C(1:10) = '1' % !!!Error
C(1:10) = [] % an 1x0 empty cell array

How can I concatenate strings in a cell array with spaces between them in MATLAB?

I want to concatenate (padding with spaces) the strings in a cell array {'a', 'b'} to give a single string 'a b'. How can I do this in MATLAB?
You can cheat a bit, by using the cell array as a set of argument to the sprintf function, then cleaning up the extra spaces with strtrim:
strs = {'a', 'b', 'c'};
strs_spaces = sprintf('%s ' ,strs{:});
trimmed = strtrim(strs_spaces);
Dirty, but I like it...
matlab have a function to do this,
ref:
strjoin
http://www.mathworks.com/help/matlab/ref/strjoin.html
strjoin
Join strings in cell array into single string
Syntax
str = strjoin(C) example
str = strjoin(C,delimiter)
Ex:
Join List of Words with Whitespace
Join individual strings in a cell array of strings, C, with a single space.
C = {'one','two','three'};
str = strjoin(C)
str =
one two three
Small improvement (?) on the answer by Alex
strs = {'a','b','c'};
strs_spaces = [strs{1} sprintf(' %s', strs{2:end})];
You can accomplish this using the function STRCAT to append blanks to all but the last cell of your cell array and then concatenate all the strings together:
>> strCell = {'a' 'b' 'c' 'd' 'e'};
>> nCells = numel(strCell);
>> strCell(1:nCells-1) = strcat(strCell(1:nCells-1),{' '});
>> fullString = [strCell{:}]
fullString =
a b c d e
Both join and strjoin are introduced in R2013a. However, the mathworks site about strjoin reads:
Starting in R2016b, the join function is recommended to join elements of a string array.
>> C = {'one','two','three'};
>> join(C) %same result as: >> join(C, ' ')
ans =
string
"one two three"
>> join(C, ', and-ah ')
ans =
string
"one, and-ah two, and-ah three"
Personally I like Alex' solution as well, as older versions of Matlab are abundant in research groups around the world.

Resources