For loop through variable names to store in structure?

조회 수: 5 (최근 30일)
Cecily Tye
Cecily Tye 2022년 4월 15일
답변: Chetan 2023년 9월 22일
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

답변 (1개)

Chetan
Chetan 2023년 9월 22일
Hello @Cecily Tye,
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:
  1. Create an array of variable names that correspond to the properties you want to access within the structure array.
  2. Utilize dot indexing to refer to the variables within the structure array using the variable names from the variable names array.
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.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by