2

I have two 1-by-n matrices A and B. A is full of strings 'test' 'test2' 'test3; and so on and B has numbers 123, 4567, 89 and so on.

How do I interweave these two to get output like

test       123
test2     4567
test3       89

as a string?

My current issue is that strings have variable lengths and so [A; B] leads to problems with mismatched dimensions.

7
  • Are your test, test2 stored as cells? And how about the numbers? You can't have strings and numbers in a regular array in MATLAB. cells are your best bet... Commented Nov 18, 2013 at 20:56
  • If the test# strings are of variable length, then how are you starring them in A currently? Either A is not a matrix and is a cell array or the strings are already padded with spaces (or some other black character). And what is class(B)? char or double? Commented Nov 18, 2013 at 20:59
  • You may need a cell array of cell arrays to deal with mismatched lengths, but in general, the approach here may be of help. Commented Nov 18, 2013 at 21:03
  • possible duplicate of MATLAB: Interweaving vectors Commented Nov 19, 2013 at 8:48
  • @thewaywewalk: I disagree. It's not possible to use the same approach when strings are involved. Commented Nov 19, 2013 at 9:55

1 Answer 1

0

You may want to concatenate an array of strings (here A is a cell array, transformed into a char array A2) with a second array of strings (B2) corresponding to your numerical values B. The double to string conversion uses sprintf. The %d stands for integer format.

This code

A = {'test'; 'test2'; 'test3'}           %cell of strings      
B = [123; 4567; 89]                      %array of doubles 

A2 = char(A);                            %array of strings
B2 = reshape(sprintf('%8d',B), 8, [])';  %convert to integer + char + reshape + transpose
[A2 B2]

produces a char array where the number part are made of 8 char

ans =

test      123
test2    4567
test3      89
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.