我是否总是需要使用单元格数组将多个值分配给struct数组? [英] Do I always need to use a cell array to assign multiple values to a struct array?

查看:81
本文介绍了我是否总是需要使用单元格数组将多个值分配给struct数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的嵌套结构数组

I've got a nested struct array like

A(1).B(1).var1 = 1;
A(1).B(2).var1 = 2;

现在,我想将var1的值更改为对每个相应值使用向量x = [3; 4]的元素.

Now I want to change the values of var1 to using the elements of the vector x = [3; 4] for each of the respective values.

结果应该是

A(1).B(1).var1 = 3;
A(1).B(2).var1 = 4;

我尝试过

% Error : Scalar structure required for this assignment.
A(1).B.var1 = x; 

% Error : Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
[A(1).B.var1] = x(:);

奇怪的是,如果x是一个单元格数组,则第二种语法有效

Curiously, if x is a cell array, the second syntax works

x = {3, 4};
[A(1).B.var1] = x{:};

幸运的是,使用mat2cell将我的数值向量转换为单元格数组并不太复杂,但这是没有for循环的唯一分配方法吗?

Luckily, it's not too complicated to convert my numeric vector to a cell array using mat2cell, but is that the only way to do this assignment without a for loop?

对嵌套结构数组进行多次赋值的正确语法是什么?我可以使用数值向量还是必须使用单元格数组?

What's the correct syntax for multiple assignment to a nested struct array? Can I use numeric vectors or do I have to use cell arrays?

推荐答案

语句

[A(1).B.var1] = x{:};

[A(1).B.var1] = deal(x{:});

(请参阅deal文档).

(see the documentation for deal).

因此您也可以写

[A(1).B.var1] = deal(3,4);

我不知道有任何其他方法可以通过单个命令将不同的值分配给struct数组中的字段.

I'm not aware of any other way to assign different values to a field in a struct array in a single command.

如果您的值在数字数组中,则可以使用

If your values are in a numeric array, you can easily convert it to a cell array using num2cell (which is simpler than the mat2cell you found).

data = [3,4];
tmp = num2cell(data);
[A(1).B.var1] = tmp{:};

通常,在这样的情况下使用struct数组是很尴尬的.如果可以,我建议您将数据存储在普通数字数组中,这样可以更轻松地同时操作许多元素.如果您坚持使用struct数组(在某些情况下很方便),只需使用for循环即可:

In general, struct arrays are rather awkward to use for cases like this. If you can, I would recommend that you store your data in normal numeric arrays, which make it easier to manipulate many elements at the same time. If you insist on using a struct array (which is convenient for certain situations), simply use a for loop:

data = [3,4];
for ii = 1:length(A(1).B)
   A(1).B(ii).var1 = data(ii);
end

另一种选择是使用 table .

The other alternative is to use table.

这篇关于我是否总是需要使用单元格数组将多个值分配给struct数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆