0

How to convert numeric array to cell array of chars and concat with chars in one line?

Example:

I have a numeric array:

[1, 5, 12, 17]

I want to convert it to a cell array of chars and concat with the chars 'Sensor ' and get:

{'Sensor 1', 'Sensor 5', 'Sensor 12', 'Sensor 17'}

Is there a way to do this in one line?

I got for now:

nums = [1, 5, 12, 17];

cellfun(@(x) ['Sensor ' num2str(x)], num2cell(nums), 'UniformOutput', 0)

Is there a simpler or more compact way?

3
  • I think, your current solution is very simple and compact. And, it's already a one-liner. So, why wasting time on saving maybe a few characters of source code? :) Commented May 15, 2019 at 12:52
  • @HansHirse: For such a simple task, it's not so compact, it seem to me that there should be a simpler - shorter solution. Commented May 15, 2019 at 12:57
  • A simpler, shorter solution might not necessarily be simpler. Readable code is almost always more important than smartly written code, unless you're competing in code obfuscation. Commented May 15, 2019 at 14:23

3 Answers 3

1

You could make it slightly neater using sprintf() and arrayfun() but not sure this saves you a lot:

nums = [1, 5, 12, 17];

arrayfun(@(x) {sprintf('Sensor %d',x)}, nums) % Gives a cell array of char array strings

arrayfun(@(x) sprintf("Sensor %d",x), nums)   % Gives an array of string strings (version 2016b onwards)

You can also use compose() in versions of MATLAB from 2016a onwards:

compose('Sensor %d', nums)  % Char array

compose("Sensor %d", nums)  % String array (version 2017a onwards)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! that's neater than my attempt.
1

Another option, which only uses functions "Introduced before R2006a", is:

A = [1, 5, 12, 17];
B = strcat('Sensor', {' '}, strtrim(cellstr(int2str(A.'))) );

This produces a column vector - so you should transpose as needed.

Comments

0

A simple alternative using strings:

>> nums = [1, 5, 12, 17];
>> cellstr("Sensor " + nums) 

ans =

  1×4 cell array

    {'Sensor 1'}    {'Sensor 5'}    {'Sensor 12'}    {'Sensor 17'}

Strings require MATLAB R2017a.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.