How to say concatenate from string 2 to end?

2 ビュー (過去 30 日間)
Zeynab Mousavikhamene
Zeynab Mousavikhamene 2019 年 12 月 29 日
編集済み: Image Analyst 2020 年 1 月 1 日
I have varying string arrays (the length of the arrays are different). I need to concatenate from the second string array to the end using hyphen (-) between. So for example if the string array is: "A" "B" "C" "D", I need to concatenate to make: "B-C-D"

採用された回答

Image Analyst
Image Analyst 2019 年 12 月 29 日
編集済み: Image Analyst 2019 年 12 月 29 日
Like this?
strings = {'A', 'B', 'C', 'D'} % Input data.
outputString = strings{2};
for k = 3 : length(strings)
outputString = sprintf('%s-%s', outputString, strings{k})
end
  1 件のコメント
Stephen23
Stephen23 2020 年 1 月 1 日
More efficient, especially for larger input cell arrays:
V = {'A','B','C','D'};
W = sprintf('-%s',V{2:end});
W = W(2:end);
Timings for 1e3 iterations
Input array with 5 elements:
Elapsed time is 0.048941 seconds. % one SPRINTF call
Elapsed time is 0.114327 seconds. % the above answer
Input array with 256 elements:
Elapsed time is 0.353918 seconds. % one SPRINTF call
Elapsed time is 3.687595 seconds. % the above answer

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

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 12 月 29 日
編集済み: Stephen23 2019 年 12 月 29 日
V = ["A","B","C","D"]
W = join(V(2:end),"-")
  6 件のコメント
Stephen23
Stephen23 2020 年 1 月 1 日
編集済み: Stephen23 2020 年 1 月 1 日
"Is it possible to accept two reponses?"
No. But you can vote for any answers that you like.
Image Analyst
Image Analyst 2020 年 1 月 1 日
編集済み: Image Analyst 2020 年 1 月 1 日
Here are the rules as I understand them:
I think the original poster can unaccept at any time. Unaccepting answers do not subtract reputation points from the answerer. Moderators can unaccept a week (I think) after it was originally posted. You can vote for any answer regardless if it's been accepted or not. You cannot vote for or accept your own answer. Voting for, and accepting, answers gives the answerer reputation points.
I voted for Stephen's clever idea to use the join() function, introduced in R2016b.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by