Specify nature/type of property
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I am writing a class in which I have the property 'food'. The property should be composed of a string specifying the type of food and a double specifying the number of calories. How do I specify this to the property? (As an example, just as I have specified 'string' to 'colour', I want to specify something for 'food')
classdef meals
properties
food
colour string
end
end
Thank you in advance for your help!
2 个评论
Wan Ji
2021-8-23
You can define another class called food
classdef food
properties
type string
calories double
end
end
回答(2 个)
Wan Ji
2021-8-23
First define the food class
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/718604/image.png)
Then define meals class
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/718609/image.png)
Now run meals in the command window, we get empty class meals with two field properties: food and colour
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/718614/image.png)
After that, look into this empty meals named ans
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/718619/image.png)
And see ans.food by double click it, food type and calories are there
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/718624/image.png)
0 个评论
per isakson
2021-8-25
编辑:per isakson
2021-8-25
... or something like:
classdef meals
properties
food (1,1) struct = struct( 'type',{'wheat'}, 'calories',{123} );
colour string
end
end
>> m.food
ans =
struct with fields:
type: 'wheat'
calories: 123
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!