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

10 ビュー (過去 30 日間)
Ben Silvester
Ben Silvester 2019 年 10 月 7 日
コメント済み: Ben Silvester 2019 年 10 月 7 日
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'
'50Hz'
'50Hz'
'50Hz'
'50Hz'
'50Hz'
'50Hz'
'50Hz'
'50Hz '
'50Hz'
'50Hz'
'50Hz'
Any help is much appreciated!
Thanks,
Ben

採用された回答

Stephen23
Stephen23 2019 年 10 月 7 日
編集済み: Stephen23 2019 年 10 月 7 日
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 =
A
>> 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'
'50HZ10'
'50HZ11'
'50HZ12'
'50HZ13'
'50HZ14'
'50HZ15'
'50HZ16'
'50HZ17'
'50HZ18'
'50HZ19'
'50HZ20'
'50HZ21'
'50HZ22'
'50HZ23'
'50HZ24'
'50HZ25'
'50HZ26'
'50HZ27'
'50HZ28'
'50HZ29'
'50HZ30'
'50HZ31'
'50HZ32'
'50HZ33'
'50HZ34'
'50HZ35'
'50HZ36'
'50HZ37'
'50HZ38'
'50HZ39'
'50HZ40'
'50HZ41'
'50HZ42'
'50HZ43'
'50HZ44'
'50HZ45'
'50HZ46'
'50HZ47'
'50HZ48'
'50HZ49'
'50HZ50'
'50HZ51'
'50HZ52'
'50HZ53'
'50HZ54'
  1 件のコメント
Ben Silvester
Ben Silvester 2019 年 10 月 7 日
Great! Thanks stephen that has fixed the problem!
Cheers

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

その他の回答 (1 件)

ES
ES 2019 年 10 月 7 日
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.'))

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by