How does on create a vector of class based on class name given as string?

9 ビュー (過去 30 日間)
John
John 2015 年 5 月 25 日
編集済み: Stephen23 2015 年 5 月 25 日
Suppose I have a function that should create and return a vector of a certain class where the class name is passed in as a char array (i.e. string). Is it possible to do this in MATLAB? It's certainly possible if you hard-code in the class name. But I would like to be able to pass into the function the name of the class I want to create an array of. The function prototype look like this:
%vector_size is the number of elements in the vector
%element_type is the type of element the vector will initially contain (a class)
function vector = createVector(vector_size, element_type)
And suppose I have a hypothetical class called ElementA, I would create a vector of ElementA with 5 elements like this:
myvector = createVector(5, 'ElementA')
How could one go about doing this?

回答 (2 件)

Stephen23
Stephen23 2015 年 5 月 25 日
編集済み: Stephen23 2015 年 5 月 25 日
With the inbuilt data classes you can use cast:
>> A = [1,2,3]
A =
1 2 3
>> class(A)
ans =
double
>> B = cast(A,'uint64')
B =
1 2 3
>> class(B)
ans =
uint64
EDIT: use cast instead of typecast, as per Walter Roberson's suggestion.
  2 件のコメント
Walter Roberson
Walter Roberson 2015 年 5 月 25 日
You would probably want cast() rather than typecast()
Stephen23
Stephen23 2015 年 5 月 25 日
Yes, in this case cast is probably the best answer. I will edit and add this.

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


Walter Roberson
Walter Roberson 2015 年 5 月 25 日
You might be able to use
zeros(1, vector_size, element_type)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by