How to add two cells with strings together?

1 回表示 (過去 30 日間)
Sarah Mullin
Sarah Mullin 2021 年 2 月 18 日
回答済み: Walter Roberson 2021 年 2 月 18 日
So my teacher asked us to download a csv file with a bunch of data in it that has 15 columns. One of the things we have to do is join together column 1 and column 14 which both contain strings. Is there a function to combine two cells together and put it into a new one? I tried this:
Column1=text1{1};
Column2=text1{14}
C=cellfun(@(x,y) [x ' ' y], A,B,'un',0)
and got this error:
"Error using cellfun. All of the input arguments must be of the same size and shape. Previous inputs had size 4946 in dimension 1. Input #3 has size 4945"
but all of the data is the same amount. please help.
  4 件のコメント
Walter Roberson
Walter Roberson 2021 年 2 月 18 日
How did you read in the data? If you used textscan it is possible for leading outputs to be 1 longer than trailing outputs, if a file ends in the middle of a line or if the format uses the wrong number of fields.
Adam Danz
Adam Danz 2021 年 2 月 18 日
What are text1{1} and text1{14}? Examples would be best.

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

回答 (2 件)

Walter Roberson
Walter Roberson 2021 年 2 月 18 日
maxlength = max(numel(A), numel(B));
A = [A(:); repmat({''}, maxlength - numel(A),1)];
B = [B(:); repmat({''}, maxlength - numel(B),1)];
C = strjoin(A, B, ' ');

Jan
Jan 2021 年 2 月 18 日
The message tells you, that A and B have different number of elements. Then a concatenation cannot work. If both have the same size, this is easier than your cellfun approach:
C = strcat(A, ' ', B);

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by