0

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.

4 Answers 4

1

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"
Sign up to request clarification or add additional context in comments.

Comments

0
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'

3 Comments

I think you need a cellfun to make this answer complete :)
@GameOfThrows: I have difficulty in understanding that what is missing in solution. Please add your solution if you think it is not complete solution
The solution which you have given works partially. I mean, I want to club that data in the same table. Your solution is creating a different cell array with the name ans. I want it under the same variable name, in your case c
0

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.

Comments

0

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() :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.