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

1 view (last 30 days)
% 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 Comments
Walter Roberson
Walter Roberson on 29 Nov 2023
Xv = arrayfun(@(IDX) q(IDX).(q(1).varName)(q(1).varIndex), 1:nval);
The assignment is more difficult to arrange.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 29 Nov 2023
Edited: Walter Roberson on 29 Nov 2023
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 Comment
Jeffrey
Jeffrey on 2 Dec 2023
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.

Sign in to comment.

More Answers (2)

Matt J
Matt J on 29 Nov 2023
Edited: Matt J on 29 Nov 2023
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 on 29 Nov 2023
Edited: Bruno Luong on 29 Nov 2023
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

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!