필터 지우기
필터 지우기

Combining to two Cells

조회 수: 1 (최근 30일)
Stephan Richtering
Stephan Richtering 2016년 1월 13일
댓글: Star Strider 2016년 1월 13일
I 've scouring the web to find a solution but not much success
p = [{2323}]; k = {'hello'};
where I want pk = {'2323hello'}
Pretty much what the concatenate function in excel would do.
Thanks, Stephan

채택된 답변

Brendan Hamm
Brendan Hamm 2016년 1월 13일
One of the issues you will face here is that what is stored in the cell array p is numeric data and concatenation of numeric data with character arrays will convert the numeric value to its ASCII representation.
>> A = [2323,'hello']
A =
hello
This is not what you are looking for. So, you need to convert the number to a character array using num2str:
>> A = [num2str(2323),'hello']
A =
2323hello
Now if this data is stored in cells we can simply concatenate the contents (which are the char arrays):
p = {2323}; % Brackets around {} are not necessary.
k = {'hello'};
A = {[num2str(p{:}),k{:}]}; % Convert num to a string, concatenate, place back in cell
If we were then to presume that these variables had a larger (but equal) size:
p = {2323;3434}
k = {'hello';'goodbye'}
for n = 1:length(p)
A(n) = {[num2str(p{n,1}),k{n,1}]};
end
disp(A)
  댓글 수: 1
Stephan Richtering
Stephan Richtering 2016년 1월 13일
Thanks Brendan. Your last solution is what I was working towards.
It also seems to work if p is a mixture of strings and numbers which is what I was looking for.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Star Strider
Star Strider 2016년 1월 13일
Using sprintf is one option:
p = {2323}; k = {'hello'};
pk = {sprintf('%d%s', p{:}, char(k))}
pk =
'2323hello'
  댓글 수: 2
Stephan Richtering
Stephan Richtering 2016년 1월 13일
Thanks for you answer Star, you're solution works.
Star Strider
Star Strider 2016년 1월 13일
My pleasure.

댓글을 달려면 로그인하십시오.


Vaibhav Awale
Vaibhav Awale 2016년 1월 13일
Hi,
This can be done using the following command:
>> pk = {[num2str(p{:}), k{:}]}
Refer to following documentation for more information about how cell array indexing works:
Hope this helps.
Regards,
Vaibhav
  댓글 수: 2
Stephan Richtering
Stephan Richtering 2016년 1월 13일
Hi Vaibhav,
Thanks for the answer. Seems to work for that example but what if I didn't know if p was a number or string would this still work?
Thanks, Stephan
Vaibhav Awale
Vaibhav Awale 2016년 1월 13일
Hi Stephan,
Interestingly "num2str" function returns the string if you give string as an input. So, this approach would work even when "p" is a string!
Regards,
Vaibhav

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by