How to perform for-loop over sequential arrays?

2 visualizaciones (últimos 30 días)
Mohamed Nedal
Mohamed Nedal el 28 de Feb. de 2019
Respondida: Bob Thompson el 28 de Feb. de 2019
Hi, I have a set of arrays stored in the workspace (X1, X2 ..., Xn) and (Y1, Y2, ..., Yn) and I would like to perform a "for loop" to match each "X" with its counterpart "Y" and save the new matched table in a sheet (the Excel file is only one).
The matching code is already prepared, but still I enter the index manually and I need a more efficient way.
Kindly check my code here:
%% THIS PART NEEDS TO BE IN FOR-LOOP STRUCTURE
Xdata = X1;
Ydata = Y1;
sheetNo = 1;
%% INITIALIZING
outputFilename = 'final_table.xlsx';
XCOL = {'UT','time_Hr','lat','long'};
YCOL = {'YEAR','DOY','Hour','pf_60Mev'};
%% MATCHING
A = array2table(Xdata, 'VariableNames', XCOL);
B = array2table(Ydata, 'VariableNames', YCOL);
%% OUTPUT
output = innerjoin(A,B,'LeftKeys','time_Hr','RightKeys','Hour');
writetable(output, outputFilename, 'Sheet', sheetNo);
Any advice or help is much appreciated.
Thanks in advance!

Respuestas (1)

Bob Thompson
Bob Thompson el 28 de Feb. de 2019
It is generally always a bad idea to label variables as x1, x2, etc. because it means you have intentions of creating multiple varialbes of the same form with different values. If this is infact what you are planning (which I believe you acknowledge here) then it is always better to put them in some form of multielement array. In your case, because you are storing entire arrays in each x I would suggest using a cell array.
for i = 1:(number of arrays)
x{i} = (x data load command);
y{i} = (y data load command);
Z{i} = x{i}(x{i}==y{i});
end
The power of this is that it allows you to do exactly what you're asking for, to put things in loops. It is not possible within matlab to dynamically change which variables you're using a loop (x1, x2, etc), but it is very possible, and rather simple to index through a multielement array (x{1}, x{2}, etc).
From what you've described wanting to do, it seems like you can put basically everything you have posted from your code into a single for loop and run it across the number of file sets you have. Just remember to index anything that you want to retain from the loop, else it will be overwritten on the next loop.

Categorías

Más información sobre Data Type Identification en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by