problem in converting a matrix of integers to vector of integers using str2num and num2str

1 回表示 (過去 30 日間)
Hello,
I have a matrix x of this form (these are example values)
1 0 0 1 0
0 1 0 0 0
0 0 0 0 1
1 0 0 1 1
I am trying to make a number out of each row so I used
y=strcat(num2str(x(:,1)),num2str(x(:,2)),num2str(x(:,3)),num2str(x(:,4)),num2str(x(:,5)));
which get me the result
'10011'
'01000'
'00001'
'10011'
Now I want to convert each string to a number but its not working.
A = str2num(y)
A =
[]
Also, I tried different method all faild beause the size of y is 4x5 and not 4x1.
why does matlab consider each char as column and how can I avoid this problem?
Thanks

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 11 日
編集済み: Ameer Hamza 2020 年 11 月 11 日
Try this
x = [
1 0 0 1 0
0 1 0 0 0
0 0 0 0 1
1 0 0 1 1];
x = char(x+'0');
y = str2num(x)
Result
>> y
y =
10010
1000
1
10011
Or a faster solution
x = [
1 0 0 1 0
0 1 0 0 0
0 0 0 0 1
1 0 0 1 1];
y = x*10.^(size(x,2)-1:-1:0)';
  6 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 11 月 11 日
編集済み: Ameer Hamza 2020 年 11 月 11 日
If you want a different number of elements in each row, then string datatype is more appropriate. For example
x = [
1 0 0 1 0
0 1 0 0 0
0 0 0 0 1
1 0 0 1 1
5 0 0 90 5
5 0 0 95 0];
y = mat2cell(string(x), 6, ones(1,size(x,2)));
y = strcat(y{:});
output
>> y
y =
6×1 string array
"10010"
"01000"
"00001"
"10011"
"500905"
"500950"
Nora Khaled
Nora Khaled 2020 年 11 月 12 日
Okay. Thank you very much this helps!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by