MATLAB - Convert Number Character array to Number Integer array/matrix?

9 ビュー (過去 30 日間)
Joe
Joe 2013 年 3 月 13 日
コメント済み: Walter Roberson 2020 年 2 月 21 日
*My problem*: Hi, I have an array *A of type char*, that reads like this:
196800271010
902589451069
052068830384
901778191098
I want to turn A into a numerical matrix that will separate the characters into individual number integers like so
[1 9 6 8 0 0 2 7 1 0 1 0
9 0 2 5 8 9 4 5 1 0 6 9
0 5 2 0 6 8 8 3 0 3 8 4
9 0 1 7 7 8 1 9 1 0 9 8]
What is the best way for this? *I've tried* str2num(A), but that treats the characters as one whole number per line (Ie first line is 1.9680) I've also tried this for loop
for i = 1:5 %the number of rows in the char array
s = num2str(A(i,:));
for t = length(s):-1:1
result(t) = str2num(s(t));
end
But this just returns the last line of the array, I want to have all of them. Thanks.

回答 (2 件)

Walter Roberson
Walter Roberson 2013 年 3 月 13 日
result = A - '0';
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 13 日
If A is a cell array
char(A)-'0'
Walter Roberson
Walter Roberson 2013 年 3 月 13 日
True. But we are given that A is of type char.

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


Mukesh Singla
Mukesh Singla 2020 年 2 月 19 日
編集済み: Walter Roberson 2020 年 2 月 21 日
your code is correct, just one thing you are need to look is that you need to store all the element in the array,
for i = 1:5
s = num2str(A(i,:));
for t = length(s):-1:1
result(i,t) = str2num(s(t));
try this you will get your result
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 2 月 21 日
Needs a couple of end statements.
What is the purpose of the num2str(A(i,:)) step when A is already a character array? num2str() applied to a character vector returns the same vector?

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

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by