I have a matrix which has with some rows and 3 columns. Each element of the matrix is a number. I want to add a new column to this matrix with each entry as a string 'abc'. How can i do that ?

1 view (last 30 days)
a=[1 4 5 ; 2 5 7];
I want to add a fourth column to my matrix such that each element of the 4th column should be a string 'abc'. Output should look like:
a=[1 4 5 ; 2 5 7 ; abc abc abc]

Answers (2)

Guillaume
Guillaume on 11 May 2018
That is not possible. A matrix is an homogeneous container. Every element is the same type. You can use non-homogeneous containers instead, such as a cell array:
a = [1 4 5 ; 2 5 7];
a = [num2cell(a); repmat({'abc'}, 1, size(a, 2))]
  1 Comment
Sahil Jain
Sahil Jain on 11 May 2018
I am getting an error by using the above line of code. Error using vertcat Dimensions of matrices being concatenated are not consistent.
Error in trial_first (line 15) my = [num2cell(x); repmat({'CCCCC'}, 1, size(x,r))];

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 11 May 2018
Use string array
out = [a;repmat("abc",1,3)]

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!