Take a vector of numbers, and convert them to a string and store in a single cell?

Say I have:
S = [1 2 3]
I want this stored in a matrix which already has stuff in it:
A =
8 1 6
3 5 7
4 9 2
And end up with something like this:
A =
8 1 6 123
3 5 7 123
4 9 2 123
I've tried playing with num2str and a few cat commands, but they all give me error. May I mention this is the first time I've been dealing with strings (which according to me, the only way to have various individual numbers stored as a "list" is to convert them to strings).

Answers (2)

If you leave as string, can't put in the numeric array; would have to use a cell array instead. OTOH, if you convert to the string and then back to numeric, you can "have your cake and eat it too"...
A(:,end+1)=num2str(sprintf('%d',s));
for your specific example above.

4 Comments

"you can have your cake and eat it too". As long as you're not concerned about the speed at which you eat your cake.
number to string and particularly string to number conversions are orders of magnitude slower than just number manipulation.
Well, yabbut... :) As noted to Star the solution then is dependent upon analyzing the number of digits and handling it specifically which takes up at least some of that time...which is, of course, what the i/o library routines are doing albeit they're set up for the most general case, not just a single purpose as here.
But, particularly for newbies, I'm all for the simplest way to implement first, then worry about optimization if it is shown the quick 'n dirty solution is, indeed, too slow.
I think I might have to go with the cell array. I need to have the 4th column "list" the S vector for each individual row... all within a single cell.
Well, you might then reconsider the whole problem and simply store the vector in a cell and format it only on output...or the new table may be just what you need???

Sign in to comment.

Another approach:
A = [ 8 1 6
3 5 7
4 9 2];
S = [1 2 3];
A = [A repmat(S*[100; 10; 1], size(A,1), 1)]

3 Comments

This has the problem that is specific to the number of digits, specifically, Star, the other handles any number (up to the limit of a double, anyway, altho it loses precision at about 15 or so... :) )
I’m just Answering the Question posted. My code can be made as robust as necessary.
Yeah, the intent was to flag that to the OP, Star, not "ding" you, per se...

Sign in to comment.

Categories

Find more on Functions in Help Center and File Exchange

Products

Asked:

on 20 Oct 2015

Edited:

dpb
on 21 Oct 2015

Community Treasure Hunt

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

Start Hunting!