Take a vector of numbers, and convert them to a string and store in a single cell?
Show older comments
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)
dpb
on 20 Oct 2015
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
Guillaume
on 20 Oct 2015
"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.
Chilean
on 20 Oct 2015
Star Strider
on 20 Oct 2015
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
dpb
on 20 Oct 2015
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... :) )
Star Strider
on 20 Oct 2015
I’m just Answering the Question posted. My code can be made as robust as necessary.
dpb
on 20 Oct 2015
Yeah, the intent was to flag that to the OP, Star, not "ding" you, per se...
Categories
Find more on Functions in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!