Replace the variable with it's contents to access a struct
5 ビュー (過去 30 日間)
古いコメントを表示
I have a list of 20+ struct that i want to do some math on. Since i need to to similar math to several of the structs i want to automate it as much as possible.
The structs are named Axxxx so i made a for loop where i create value in the variable that is the name of the struct. How do i then use whats in the variable with the struct.
First = 'A00';
for k = 1 : 21
A_temp = append(First,num2str(k-1));
A_temp.new_column = A_temp.old_column/15; <--- This does not work, but might display what i want to do.
end
A_temp now contains say 'A0020' as a string, how do i access that struct using the variable A_temp containing 'A0020'
A_temp.kanal1 becomes A0020.kanal1
I hope my question is understandable
Kind Regards
David
3 件のコメント
Stephen23
2022 年 10 月 4 日
編集済み: Stephen23
2022 年 10 月 4 日
"The structs are named Axxxx ..."
And that is the start of your problems, right there.
"Since i need to to similar math to several of the structs i want to automate it as much as possible."
And so you designed your data to make that automation easier, e.g. by creating one cell/structure array which can be trivially accessed using basic, neat, very efficient indexing. Or did you skip that important step?
"...so i made a for loop where i create value in the variable that is the name of the struct. How do i then use whats in the variable with the struct."
Aaaahh, unfortunately that bad data design forces you into writing slow, complex, inefficient, insecure, obfuscated, buggy code which is difficult to debug:
Accessing your data would be trivial and very efficient with better data design e.g. using one structure array would let you use indexing. So far you have not told us the most important information: how did you get those tables into the workspace? The place where they are created in the workspace is the correct place to fix your code, e.g. by LOADing into an output variable instead of LOADing directly into the workspace.
回答 (1 件)
Vishesh
2022 年 10 月 7 日
- You can do it by saving all the variables present in the workspace in a table first and then perform your operation in the table.
- Here i am taking "A001" and "A002" as an example.
- You can optimize some of the lines of code by yourself.
clear;
A001=struct('a',2,'b',10);
A002=struct('a','4','b',20);
save('var.mat');
clear;
Tab=struct2table(load('var.mat'),'AsArray',true);
First = 'A00';
var_name=Tab.Properties.VariableNames;
var_names=[];
for i=1:length(var_name)
var_names=[var_names ;var_name{i}];
end
for k = 1 : 21
A_temp = append(First,num2str(k-1));
for i=1:length(var_names(:,1))
if(strcmp(var_names(i,:),A_temp))
Tab.(i).a=Tab.(i).a/2;
Tab.(i).b=Tab.(i).b/5;
end
end
end
clear A_temp First i k var_names var_name
table2struct(Tab)
0 件のコメント
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!