- Create an array of variable names that correspond to the properties you want to access within the structure array.
- Utilize dot indexing to refer to the variables within the structure array using the variable names from the variable names array.
For loop through variable names to store in structure?
5 次查看(过去 30 天)
显示 更早的评论
I have five different matrices from five different locations. The columns are the same variables in each matrix. I'm trying to streamline my code and pull all of the variables into one non-scalar structure, with each row of the structure corresponding to the location and each column corresponding to the variables of interest. I don't want to pull out all of the column variables, as there are a ton and some are not relevant to what I'm doing. So ideally what I'd like to do is something like in this for-loop (I'm aware that the syntax on the inner loop is completely incorrect, just trying to relay the idea). What would the best way to do this be? Any input is appreciated!
loc.names = {'ALE', 'AQM','NAP','MKO','CAR'}; % there are also matrices with these names containing all of the data for each location
n = length(loc.names);
var.names = {'mtime', 'year', 'T_top', 'T_mid', 'T_bot'};
var.cols = [1, 2, 55, 56, 57]; % corresponding column in each matrix
m = length(var.names);
for i = 1:n
mooring(i).name = loc.names(i);
for j = 1:m
mooring(i).%v, var.names(j) = loc_matrix(:,var.cols(j))
end
end
0 个评论
回答(1 个)
Chetan
2023-9-22
I understand that you are attempting to access the properties of structure variables using a loop, but you're facing difficulties in doing so. I recommend the following approach:
By implementing this method, you should be able to access the desired structure properties successfully.
You can refer to the following code for more details:
loc.names = {'ALE', 'AQM', 'NAP', 'MKO', 'CAR'};
n = length(loc.names);
var.names = {'mtime', 'year', 'T_top', 'T_mid', 'T_bot'};
var.cols = [1, 2, 55, 56, 57];
m = length(var.names);
mooring = struct(); % Initialize the structure
for i = 1:n
mooring(i).name = loc.names{i};
loc_matrix = load([loc.names{i} '_matrix']); % Load the matrix for the location
for j = 1:m
var_name = var.names{j};
col_index = var.cols(j);
mooring(i).(var_name) = loc_matrix(:, col_index);
end
end
I hope these suggestions help you resolve the issue you are facing.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!