Reputation: 55
I have data in different cells (mostly strings) and I would like to bring some of the data in one cell and keep the rest of the data as it is.
For instance:
A = {'1' '2' '3' '4' '5'; '6' '7' '8' '9' '10'; '11' '12' '13' '14' '15'};
The desired output should be:
B = {'1' '2' '3 4 5'; '6' '7' '8 9 10'; '11' '12' '13 14 15'};
The numbers must be separated by a space.
Upvotes: 0
Views: 94
Reputation: 38032
Just in case anyone here has MATLAB prior to R2013a (which does not have strjoin()
) or R2013b (which does not have join()
):
% The original
A = { '1' '2' '3' '4' '5'
'6' '7' '8' '9' '10'
'11' '12' '13' '14' '15'};
% The new
B = A;
B(:,3) = strcat(arrayfun(@(ii) sprintf('%s ', B{ii,3:end-1}), 1:size(B,1), 'UniformOutput', false)', ...
B(:,end));
B(:,4:end) = []
which is so fugly that it only serves as a vindication for strjoin()
:)
Upvotes: 0
Reputation: 706
Using string and join in 16b makes this a bit easier than using strjoin since join works with the dimensionality of matrices.
>> A = string({'1' '2' '3' '4' '5'; '6' '7' '8' '9' '10'; '11' '12' '13' '14' '15'});
>> [A(:,1:2) join(A(:,3:end),2)]
ans =
3×3 string array
"1" "2" "3 4 5"
"6" "7" "8 9 10"
"11" "12" "13 14 15"
Upvotes: 1
Reputation: 1
Use the strjoin method.
strjoin(A(1,1:3))
returns '1 2 3'
// Automatically has spaces.
This MATLAB method defaults to a space delimeter. However.... If you should need an additional delimeter use this
strjoin(A(1,1:3),'*')
returns '1*2*3'
B = A(:,1:2);
for count = 1:size(A)
B(count,3)=cellstr(strjoin(A(count,3:5)));
end
This is how I would do what you wanted above.
Upvotes: 0
Reputation: 3364
c{1} = 'a'
c{2} = 'b'
c{3} = 'c'
>> c{2} = 'b'
c =
'a' 'b' 'c'
>> {char(c)'}
ans =
'abc'
>> {strjoin(c, ' ')}
ans =
'a b c'
Upvotes: 0