How can I call a matrix entry inside a struct (using sprintf)?
5 次查看(过去 30 天)
显示 更早的评论
Hello all together,
I'd like to know if there is an easy way to call a matrix entry inside of a struct. Let's say I have a struct with a field called A, that contains a matrix. I need to plot certain entries of that matrix for each row in the struct. I know there are more elegant ways to store the data, but for the sake of clarity on the user side of the final code, I need to store the data in a struct with the field names as headlines. The user will give the matrix (field) name (A or B or C ....) and the entry's row and column to be plotted. For each row in the struct the matrix entry will be stored in a vector, that will be plotted afterwards. Since the code is meant to be as short and simple as possible, I thought the most simple way of doing this might be something like:
solution(1,1).A = rand(2);
solution(2,1).A = rand(2);
solution(3,1).A = rand(2);
option = 'A(2,2)';
limitv = zeros(size(solution,1),1);
for p=1:length(limitv)
limitv(p,1) = solution(p).(sprintf(option));
end
Obviously this doesn't work, because 'A(2,2)' is not a valid field name (works for single entries, but obv not for entries inside of a matrix), but maybe you get the idea of how it should look like. I thought about separating the row and column indices, but that would mean I need to insert many many lines of IF conditions, because there are many many different matrices and other vectors stored in the struct. Is there any way to utilize the sprintf function or any other efficient way to concatenate the field name and the indices? Or even utilize the vertcat function in a short and efficient way?
2 个评论
James Tursa
2021-3-15
编辑:James Tursa
2021-3-15
Will the choice always be a single element of a particular field? I.e., you won't be picking off ranges such as A(2,3:4)?
If you have to use this struct arrangement and character entry for desired element, you may be forced into some relatively ugly code downstream (deep data copies, eval, mex routine, etc.).
采纳的回答
Stephen23
2021-3-15
编辑:Stephen23
2021-3-15
"Since the code is meant to be as short and simple as possible.... Is there any way to utilize the sprintf function or any other efficient way to concatenate the field name and the indices?"
No, because your approach is fundamentally complex and inefficient. Changing how you generate the string makes no difference: you will always require some munging of data to convert the string into usable indices.
A much better approach using a comma-separated list, and store numeric data as numeric:
S(1,1).A = rand(2);
S(2,1).A = rand(2);
S(3,1).A = rand(2);
F = 'A'; % fieldname
X = {2,2}; % indices
S(3).(F)(X{:})
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!