MATLAB: Combine columns of multiple arrays using for loop

columnsforfor looploop

I am trying to use a for loop to combine columns of multiple arrays in MATLAB.
I want to take column 1 (or i) of the first variable (lat) and combine this with column 1 (or i) of the other three variables (lon, rng, and z), similar to the output expected from the code below.
if true
% Example of output wanted:
test = [lat(:,1) lon(:,1) rng(:,1) z(:,1)];
However, I want to repeat this for all 360 columns in each of the four arrays (see attached matlab file).
How would I do this with a for loop?

Best Answer

Preferably the output would be vertical with the ability to decipher where one column has ended and another starts
Is this for storage or display?.
If for storage, then simply concatenate the variables.
allvars = cat(3, lat, lon, rng, z); %concatenate the variables in the 3rd dimension
%allvars(:, n, :) correspond to column n of the variables
If you wish you can then permute dimensions so that your original variables are then columns,
allvars = permute(cat(3, lat, lon, rng, z), [1 3 2]);
%allvars(:, :, n) corresponds to column n of the variables
i.e. have another column which labels the first 967 rows as 1 and then the next 967 rows as 2, etc
That can be done as well:
allvars = [reshape(cat(3, lat, lon, rng, z), [], 4), repelem(1:size(lat, 2), size(lat, 1))']
The last column is the index of the original column