how to add string matrix to numeric matrix?

115 views (last 30 days)
eri
eri on 26 Oct 2012
example:
from
a=[rice;corn;wheat]
b=[3;4;3]
become
c=[rice 3;corn 4;wheat 3]

Answers (3)

José-Luis
José-Luis on 26 Oct 2012
You could use cell arrays:
a={'rice';'corn';'wheat'};
b={3;4;3};
your_result = cellfun(@(a,b) [a ' ' num2str(b)],a,b,'uniformoutput',false);
  4 Comments
eri
eri on 26 Oct 2012
Edited: eri on 26 Oct 2012
it did work, but the result is in one column, is it possible to make it two columns, for the example above i have two 3x1 matrix and i want the result to be 3x2 matrix?
Walter Roberson
Walter Roberson on 26 Oct 2012
[a, strcat({' '}, num2str(b))] %output will be cell 3x2 of strings

Sign in to comment.


Walter Roberson
Walter Roberson on 26 Oct 2012
No, numeric arrays can never contain strings.
Cell arrays can contain both strings and numbers, in separate elements.
c = {'rice', 3; 'corn', 4; 'wheat', 3};
  2 Comments
eri
eri on 26 Oct 2012
my question is that i already have a and b, and what should i do to get output like c by operating a and b?
Walter Roberson
Walter Roberson on 26 Oct 2012
Edited: Walter Roberson on 26 Oct 2012
c = [a, num2cell(b)]; %output will be cell 3x2 first col strings second col numeric

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 26 Oct 2012
a={'rice';'corn';'wheat'}
b=[3;4;3]
c=arrayfun(@(x) [a{x} ' ' num2str(b(x))],1:3,'un',0)

Categories

Find more on Characters and Strings 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!