# NetCDF File Assign Variable Loop from Array

4 views (last 30 days)
Mark Nakers on 23 Apr 2020
Edited: per isakson on 24 Apr 2020
I have a row vector that consists of 13 heights (in meters):
z = [1.5,3,4.5,6,7.5,9,10,11,12.5,14,18,23,29];
I'm attempting to retreive data from a NetCDF (.nc) file, which has "built in" variables.
Each height has two variables, assocaited with it: u and v, each of which are a 60x14400 double. (The first dimension is the
sampling frequency (60 Hz). The second dimension is time in seconds since an initial start time.)
For example, to load 1.5m u and v and assign to variables "1_5u" and "1_5v" I would do:
For 10m u and v, I would do
And so on.
However, my main goal/question is: How could I create a loop to reference each height in z and load each variable?
Here's how I started:
for i = z
j = mod(i,1);
if j == .5
fNameu = ['u_' num2str(fix(i)) '_5m_vt'];
fNamev = ['v_' num2str(fix(i)) '_5m_vt'];
else
fNameu = ['u_' num2str(i) 'm_vt'];
fNamev = ['v_' num2str(i) 'm_vt'];
end
end
I have three questions here:
1) How can I assign two variables to each height with unique variable names for each? (Getting 26 variables in total)
2) How do I account for the fact some elements in z have a decimal, but the var name in the file is an underscore? (It is also important to keep the 'z' array as I'm referencing it in other locations)
3) How could I then take each of these variables and create 26 additional variables WITHIN THIS LOOP to take the mean of each variable over the first dimension (i.e. average over the first dimension of 60 frequencies) over a specific time period (the second dimension)
For example for 1.5m, something like:
uMean1_5 = mean(u_1_5(timeRef),1);
vMean1_5 = mean(v_1_5(timeRef),1);
How can I also include this within the loop?

per isakson on 24 Apr 2020
I doubt it is a good idea to create that many variables. See TUTORIAL: Why Variables Should Not Be Named Dynamically (eval)
The first character of a variable name must be an English letter. 10u is not legal.
Mark Nakers on 24 Apr 2020
Let’s disregard the mean- how can I go about doing it anyways?

per isakson on 24 Apr 2020
Edited: per isakson on 24 Apr 2020
by
where the value of txt is the name of the variable to be created
and where
function assign( Name, Value )
% assign assigns the value of Value to a variable named Name
%
% Example:
% assign( 'M', magic(5) )
% for k = 1:11, assign( sprintf( 'var%d', k ), k ), end
narginchk( 2, 2 )
assert( isvarname(Name), 'assign:IllegalName' ...
, 'First input argument, "%s", must be a legal name', Name )
assignin( 'caller', Name, Value );
end