Reputation: 147
I have a vector with certain numbers as:
A=[1 2 3];
And I need to get another vector as:
B=[G1 G2 G3];
Since I cannot mix chars and doubles, I tried to convert the matrix A into a cell array doing:
num2cell(num2str(A))
And then do:
strcat(A, 'G')
To obtain the desired result. But doing the num2cell I obtain cell values for thee white spaces (so instead of obteniendo a cell array of 3x1, I obtain Nx1), and then the concatenation with the letter 'G' becomes wrong.
Upvotes: 0
Views: 365
Reputation: 413
If you want B
to be a single string with all these values you can simply use sprintf
. This function accepts vectors as it's second argument so it's very easy to add the same character to every value in A
.
B = sprintf('G%d ', A);
Note that this will leave you with a trailing space after your last entry (i.e. 'G1 G2 G3 '
) but this can easily be removed though with:
B(end) = [];
See the documentation on sprintf for more examples.
Upvotes: 0
Reputation: 65460
The issue is that num2cell
makes every single character a separate cell array element by default.
num2cell(num2str(A))
% '1' ' ' ' ' '2' ' ' ' ' '3'
To simply concatenate G
to every element, you can just use numstr
on the column-vector version of A
which places each string representation of each number in A
on a new line. strcat
would then prepend a 'G'
to each line. If you want it as a cell array, we can wrap that in a cellstr
call to get a cell array.
output = cellstr(strcat('G', num2str(A(:))))
Alternately, you could just use sprintf
on each element in A
output = arrayfun(@(x)sprintf('G%d', x), A, 'UniformOutput', false)
Upvotes: 2