What is the difference between A={1 2} and A = { '1','2'} and how to convert one from other ?

11 ビュー (過去 30 日間)
Geethanjali
Geethanjali 2025 年 6 月 16 日
編集済み: John D'Errico 2025 年 6 月 17 日
What is the difference between A={1 2} and A = { '1','2'} and how to convert one from other ?
  1 件のコメント
Stephen23
Stephen23 2025 年 6 月 17 日
In addition to the comments below, it is also worth mentioning that unless you have a particular reason to store scalar numerics in a cell array, using a numeric array would be more efficient and likely make processing your data easier:
A = [1,2]

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

採用された回答

Epsilon
Epsilon 2025 年 6 月 16 日
編集済み: Epsilon 2025 年 6 月 16 日
Hi Geethanjali,
A = {1 2} represents a 1x2 cell array with two double type numeric values, 1 and 2, while A = {'1', '2'} represents a 1x2 cell array with two char type charachter values '1' and '2'. To convert char to double, use the inbuilt function 'str2double', while the function 'num2str' can be used for the reverse conversion. Since MATLAB represents strings as arrays of characters, the above-mentioned functions have the term 'str'.
%To convert the cell arrays
A = {'1', '2'};
A = cellfun(@str2double, A, 'UniformOutput', false);
disp(A)
{[1]} {[2]}
B = {1 2};
B = cellfun(@num2str, B, 'UniformOutput', false);
disp(B)
{'1'} {'2'}
%Converting only one element
A='1'
A = '1'
A=str2double(A)
A = 1
B=1
B = 1
B=num2str(B)
B = '1'
  3 件のコメント
Epsilon
Epsilon 2025 年 6 月 16 日
Thank you for the clarification.

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

その他の回答 (1 件)

John D'Errico
John D'Errico 2025 年 6 月 16 日
編集済み: John D'Errico 2025 年 6 月 17 日
Think of it like this:
1 is a "number" as stored in MATLAB, as is 2.
X = [1 2]
X = 1×2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
whos X
Name Size Bytes Class Attributes X 1x2 16 double
X is stored in double precision. We can add them, subtract them, etc.
But in character form, they are more like pictures of numbers. Text representations thereof. You cannot add them and get an expected result. You cannot do arithmetic on them, and have it do anything that will make sense.
Y = '1'
Y = '1'
whos Y
Name Size Bytes Class Attributes Y 1x1 2 char
You can convert them to numbers, using as has been shown, str2double. But the two forms are stored completely differently.
In the end, both 1 and '1' are representations of the number we fondly think of as "one". What can matter is how it is stored, and how that representation can then be used. Is either truly the number 1? That is a rather philosophical question, about something that is best described as a mathematical concept used as a measure.

カテゴリ

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