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).

回答 (2 件)

dpb
dpb 2015 年 10 月 20 日
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 件のコメント

Guillaume
Guillaume 2015 年 10 月 20 日
"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.
dpb
dpb 2015 年 10 月 20 日
編集済み: dpb 2015 年 10 月 20 日
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
Chilean 2015 年 10 月 20 日
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.
dpb
dpb 2015 年 10 月 20 日
編集済み: dpb 2015 年 10 月 21 日
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???

サインインしてコメントする。

Star Strider
Star Strider 2015 年 10 月 20 日
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 件のコメント

dpb
dpb 2015 年 10 月 20 日
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
Star Strider 2015 年 10 月 20 日
I’m just Answering the Question posted. My code can be made as robust as necessary.
dpb
dpb 2015 年 10 月 20 日
Yeah, the intent was to flag that to the OP, Star, not "ding" you, per se...

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

質問済み:

2015 年 10 月 20 日

編集済み:

dpb
2015 年 10 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by