使用动态数组访问结构以进行索引

accessing structures using dynamic arrays for indexing

为了计算二维结构系统的总质量,我获得了有关面积、属性(存储在 "props"-结构数组中)和 material(存储在 "mats"-结构数组)每个结构组件。

我可以遍历元素总数并按面积 * 厚度 * 密度单独计算质量,但我想这样做而不必使用 for 循环。

% This is the database
area = [100 300 500];

props.shell(1).thic = 5;
props.shell(2).thic = 10;

mats.alu(1).rho   = 10;
mats.alu(2).rho   = 15;
mats.steel(1).rho = 20;
mats.steel(2).rho = 25;

比如我要计算元素1和3的质量,确定了以下查表:

% beforehand computed field names and indices
a_idx  = [1 3] 

p_name = {'shell' 'shell'};
p_idx  = [1 2];

m_name = {'alu' 'steel'};
m_idx  = [2 1];

% this works
mass = 0;
for i = 1 : numel(a_idx)
    mass = mass + area(a_idx(i)) * props.(p_name{i})(p_idx(i)).thic * mats.(m_name{i})(m_idx(i)).rho
end

这就是我希望它的工作方式:)

mass = sum(area(a_idx) .* [props.(p_name)(p_idx).thic] .* [mats.(m_name)(m_idx).rho])

我已经试过了

mass = sum(area(a_idx) .* [props.(p_name{:})(p_idx).thic] .* [mats.(m_name{:})(m_idx).rho])

但遗憾的是我无法使用正确的字符串建立索引...

您尝试使用 dynamic field references with a cell array of field names is the sticking point here. There's really no good shorthand notation to do it. The only option I can think of is to convert the top-level structure array into a cell array using struct2cell 的事实,但这创建了一种看起来更复杂的方法,所有这些都是为了避免非常简单且老实说可能更有效的 for 循环。

如果你很好奇,下面是避免 for 循环的样子:

% Get thickness:
propData = struct2cell(props);
[~, index] = ismember(p_name, fieldnames(props));
propData = vertcat(propData{index});
thickness = [propData(sub2ind(size(propData), 1:numel(p_name), p_idx)).thic];

% Get density:
matData = struct2cell(mats);
[~, index] = ismember(m_name, fieldnames(mats));
matData = vertcat(matData{index});
density = [matData(sub2ind(size(matData), 1:numel(m_name), m_idx)).rho];

% Calculate mass:
mass = sum(area(a_idx).*thickness.*density);