【问题标题】:How to declare an array of structure and access (write to/read from) individual fields in Matlab?如何在 Matlab 中声明结构数组和访问(写入/读取)各个字段?
【发布时间】:2015-04-17 15:13:31
【问题描述】:

我正在尝试在 Matlab 中声明一个结构:

book = struct('name', '', 'author','', 'price,'', 'date_of_pub','')

num_books = input('enter number of books')

然后声明一个数组 (list_of_books),其中包含有关若干 (num_books) 书籍的这些信息。

在 C 语言中,我会做这样的事情(示例代码,不详述)

typedef struct {
char name[20];
char author[20];
float price;
date date_of_pub; //'date' being another predefined struct containing dd, mm, yy
}book;

int main()
{
int num_books = 0;

printf("enter number of desired books\n");
scanf("%d", &num_books);

book *list_of_books = malloc(num_books * sizeof(book));

for(i = 0; i < num_books; ++i){
    printf("enter name of book #%d:\n",i+1);
    scanf("%s", list_of_books[i].name);
    //same for the other info
}

/* 另一个循环打印书籍信息,这可能是一个单独的函数等 */

我知道http://www.mathworks.com/help/matlab/structures.html,但我正在寻找具有类似实现的 Matlab 代码示例以供学习。或者,如果您有任何其他我可以查看的资源以及代码示例,我们将不胜感激。谢谢。

【问题讨论】:

  • 而且数组的所有字段也应该有空值?
  • 不一定,但我想实现一个“for循环”遍历数组,让用户填写结构的每个字段。
  • 哦。那我把你的问题弄错了

标签: arrays matlab structure


【解决方案1】:

要创建包含num_books 副本的list_of_books 数组list_of_books,只需使用repmat

list_of_books = repmat(book, num_books, 1);

直接做(没有先定义book):

book = struct('name',repmat({''},num_books,1), 'author','', 'price','', 'date_of_pub','');

后者使用struct的语法multiple-value systax(重点是我加的):

S = struct(field1',VALUES1,'field2',VALUES2,...)

创建一个具有指定字段和值的结构体数组。价值 数组VALUES1VALUES2 等必须是相同的元胞数组 大小、标量单元格或单个值。对应的元素 值数组被放入对应的结构体数组元素中。 结果结构的大小与值的大小相同 元胞数组或 1×1(如果没有任何值是元胞)。

请注意,为一个字段提供多个值就足够了(我在本例中使用了第一个),而其他字段会自动复制。

【讨论】:

  • 谢谢。我需要一个 for 循环(对于 i=1:num_books)并要求用户为数组中的每本书单独填写结构的每个字段。尝试使用 liste_of_books(i).name = input ('enter name of book') 但它失败了。关于如何解决这个问题的任何建议?
  • 您需要input 中的标志's' 来接受字符串输入:list_of_books(i).name = input ('enter name of book: ', 's')
  • 谢谢!在这里进一步推动我的运气,可以格式化“输入”吗?像 list_of_books(i).name = input ('输入书名 %d: ', i, 's') 或者“输入”是不可能的?
  • 你不能直接这样做。但是input 的第一个参数可以是sprintf 的结果(如在C 中)。所以:list_of_books(i).name = input(sprintf('enter name of book number %d: ', i), 's')
  • 非常感谢您对我的沉迷和非常有用的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多