is there a way to perform this task w/o using loops?

2 次查看(过去 30 天)
% this script sets up a structure p. In this minimal version, p only contains 1 variable.
% then expands it into a 1x4 structure array q
% and inserts values into one of the variables. (Only the L variable is shown here.)
% and then retrieves the values
% The variable is a row vector and has name given by varName
% The values go into (and are retrieved from) the 2nd element of L because varIndex = 2;
p.varName = 'L';
p.varIndex = 2;
p.L = [3, 4, 5];
nval = 4;
q = repmat(p,1,nval);
vals = [6 7 8 9];
% Insert values
for i=1:nval
q(i).(p.varName)(p.varIndex) = vals(i);
end
Xv = zeros(1,nval);
% Retrieve values
for i=1:nval
Xv(i) = q(i).(q(1).varName)(q(1).varIndex);
end
  3 个评论
Walter Roberson
Walter Roberson 2023-11-29
Xv = arrayfun(@(IDX) q(IDX).(q(1).varName)(q(1).varIndex), 1:nval);
The assignment is more difficult to arrange.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2023-11-29
编辑:Walter Roberson 2023-11-29
The more general vectorized strategy would probably be to set up cell arrays of values, and then use the fact that when you struct() and pass a cell array, then the output is a struct array the size of the cell array.
  1 个评论
Jeffrey
Jeffrey 2023-12-2
Understood. I like this answer the best because it's elegant, but will probably stick with the loop instead of introducing cell arrays into my code, to keep it simple.

请先登录,再进行评论。

更多回答(2 个)

Matt J
Matt J 2023-11-29
编辑:Matt J 2023-11-29
There are ways to do it without loops, but doing it without loops will be of no benefit to you. It will take more lines of code, consume more memory, and run more slowly.
p.varName = 'L';
p.varIndex = 2;
p.L = [3, 4, 5];
nval = 4;
q = repmat(p,1,nval);
vals = [6 7 8 9];
% Insert values
TMP=vertcat(q.(p.varName));
TMP(:,p.varIndex)=vals;
TMP=arrayfun(@(i)TMP(i,:), 1:nval,'uni',0);
[q.(p.varName)]=deal(TMP{:});
q.L
ans = 1×3
3 6 5
ans = 1×3
3 7 5
ans = 1×3
3 8 5
ans = 1×3
3 9 5

Bruno Luong
Bruno Luong 2023-11-29
编辑:Bruno Luong 2023-11-29
You might consider store in table instead
NOTE: using table would be more convenient to access data, not necessary faster
p.varName = "L";
p.varIndex = 2;
nval = 4;
q = repmat(p,1,nval);
vals = [6 7 8 9];
% Insert values
for i=1:nval
q(i).(p.varName)(p.varIndex) = vals(i);
end
T = struct2table(q)
T = 4×3 table
varName varIndex L _______ ________ ______ "L" 2 0 6 "L" 2 0 7 "L" 2 0 8 "L" 2 0 9
T.varName(1)
ans = "L"
T.(T.varName(1))
ans = 4×2
0 6 0 7 0 8 0 9
T.(T.varName(1))(:,T.varIndex(1))
ans = 4×1
6 7 8 9

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by