필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Jeffrey
Jeffrey 2023년 11월 29일
댓글: Jeffrey 2023년 12월 2일
% 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.
Jeffrey
Jeffrey 2023년 12월 2일
Understood. Thank you.

댓글을 달려면 로그인하십시오.

채택된 답변

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