当前位置: 动力学知识库 > 问答 > 编程问答 >

How to stick char array with strcat MATLAB

问题描述:

This is the question:

I have the next 3 variables:

A=['a1';'a2';'a3']';

B=['b1';'b2';'b3']';

C=['c1';'c2';'c3']';

And I want to stick all of them with an strcat, and if a do this:

D=strcat('',A,'-',B,'-',C,'')

D =

a1-b1-c1

a2-b2-c2

a3-b3-c3

But if I want to make an space, like this:

D=strcat(['',A,' - ',B,' - ',C,''])

I got this error:

CAT arguments dimensions are not consistent.

Can somebody help me? Thanks!

网友答案:

The problem is the brackets. Remove them. Also, you don't need those empty strings:

>> strcat(A, '   -   ', B, '   -   ', C)
ans =
    a1   -b1   -c1
    a2   -b2   -c2
    a3   -b3   -c3

Note that trailing spaces are removed by strcat. To prevent that from happening, use cells; but then the result will be a cell array of strings, not a 2D char array:

>> strcat(A, {'   -   '}, B, {'   -   '}, C)
ans = 
    'a1   -   b1   -   c1'
    'a2   -   b2   -   c2'
    'a3   -   b3   -   c3'

To obtain a 2D char array, use horizontal concatenation. You'll need repmat to make the number of rows match:

>> [ A, repmat('   -   ',size(A,1),1), B, repmat('   -   ',size(A,1),1), C ]
ans =
    a1   -   b1   -   c1
    a2   -   b2   -   c2
    a3   -   b3   -   c3
分享给朋友:
您可能感兴趣的文章:
随机阅读: