Clear Filters
Clear Filters

Numerical cell value changes to random symbols when using strcat - help needed

6 views (last 30 days)
I have a short bit of code assigning test numbers to variable names. I have a variable (testno) as cell type with the test number 1 - 54, when I try to join this with another cell type array of the same size (frequency) the numerical values in testno turn to random symbols.
I can't seem to find a reason why, I'm realively new to Matlab so chances are I'm not doing this right.
Sample code below:
>n1 = 54;
>testno = [1:54]
>testno = num2cell(testno.');
>testvariable = strcat(frequency, testno);
frequency is a celll type with 50Hz repeated 54 times in a single column.
I have also tried concatnenating tesno with 'T' and the same happens.
testvariable ends up like below but with more symbols this text editor can't show.
'50Hz '
Any help is much appreciated!

Accepted Answer

Stephen23 on 7 Oct 2019
Edited: Stephen23 on 7 Oct 2019
They are not random characters at all, they are in fact exactly the characters with exactly those character codes that you specified (most of the ones you generated are non-printing control characters):
"I can't seem to find a reason why,"
When you concatenate a character vector and a numeric MATLAB does not implicitly convert the numeric values into a string representing the values stored in the numeric: it converts the numeric into the characters whose codes are given by those numeric values. For example:
>> X = 'A';
>> X(2) = 4 % this does NOT create the character vector 'A4' !
X =
>> double(X) % check the character codes:
ans =
65 4
You can use num2str or sprintf to convert numerics to character arrays representing the numeric values, e,g.:
>> strcat('50HZ',cellstr(num2str((1:54).')))
ans =
'50HZ 1'
'50HZ 2'
'50HZ 3'
'50HZ 4'
'50HZ 5'
'50HZ 6'
'50HZ 7'
'50HZ 8'
'50HZ 9'

More Answers (1)

ES on 7 Oct 2019
Since your testno is numeric, the when you do strcat, the number is converted to a character.
What you want is that number to be converted to string (use: num2str). Use
testno = num2cell(num2str(testno.'))


Find more on Characters and Strings in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!