Joining two string arrays, line by line in matlab without using a for loop through the array

StackOverflow https://stackoverflow.com/questions/23638194

  •  21-07-2023
  •  | 
  •  

Pregunta

I know this is simple. I just can't remember how to do this!

What I have:

>> filenames

filenames = 

    '0F06EB0A338A35CDBD33356A470D5052'
    '75168DAA9A225EF6F79DDA5014CA69FD'
    'DAEE5EE3E65584655CE208F15D1F6F43'
    'EF026066C8BAB5D32F9B67872C69451D'

What I want:

>> varnames

varnames = 

    'x0F06EB0A338A35CDBD33356A470D5052'
    'x75168DAA9A225EF6F79DDA5014CA69FD'
    'xDAEE5EE3E65584655CE208F15D1F6F43'
    'xEF026066C8BAB5D32F9B67872C69451D'

(I know about genvarnames but that's not what I'm going to use for this, since I need x in front of all of them).

What I've tried so far

>> ['x' filenames{1}]

ans =

x0F06EB0A338A35CDBD33356A470D5052

Great success! Now I just need to generalize this to the whole thing. However, I'm not going to use a for-loop, since I'm not an ogre.

Let's try this:

>> ['x' filenames{:}]

ans =

x0F06EB0A338A35CDBD33356A470D505275168DAA9A225EF6F79DDA5014CA69FDDAEE5EE3E65584655CE208F15D1F6F43EF026066C8BAB5D32F9B67872C69451D

Weeeell, almost, maybe repmat can help! Since obviously:

>> repmat('x', 4, 1)

ans =

x
x
x
x

That's all I need to get this working, right??

>> varnames= [repmat('x', 4, 1) filenames{:}]
??? Error using ==> horzcat
CAT arguments dimensions are not consistent.

Wrong. Perhaps it's as simple as:

>> varnames= [repmat('x', 4, 1) filenames(:)]
??? Error using ==> horzcat
CAT arguments dimensions are not consistent.

What if I just remove them alltogether...?

>> varnames= [repmat('x', 4, 1) filenames]
??? Error using ==> horzcat
CAT arguments dimensions are not consistent.

... Let's just pepper {} all over this

>> varnames= {repmat('x', 4, 1) filenames{:}}

varnames = 

  Columns 1 through 4

    [4x1 char]    [1x32 char]    [1x32 char]    [1x32 char]

  Column 5

    [1x32 char]

... crap.

Well I'm out of ideas, and I won't bother you with more of my failed attempts. I refuse to believe that a for loop is the only way to do this!

¿Fue útil?

Solución

http://www.mathworks.com/help/matlab/ref/strcat.html

"Concatenate strings horizontally"

strcat('x',StringMatrix)

Test:

>> SA2
SA2 = 
    'four'    'five'    'six'
>> strcat('x',SA2)
ans = 
    'xfour'    'xfive'    'xsix'
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top