How to automatically create new variables from existing column vector?
Afficher commentaires plus anciens
I'm new to MATLAB and need a little help. I have daily precipitation data for 5 years on excel. I need to create 5 new variables (y1, y2, y3, y4, y5) from that data which represent each year as follows: y1=P(1:365); y2=P(366:730); y3=P(731:1095); y4=P(1096:1460); y5=P(1461:1826) where P is the column vector that contains the daily precipitation data for five years, then P is a 1-by-1826 matrix (since 4 years have 365 days each and the leap year 366). Is there any way to automatically generate this in MATLAB in a way that if I want to add more years of data, MATLAB could generate the variables y6, y7, y8....yn? Thanks in advance.
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 11 Juin 2017
Use reshape to put each year into one column. For example:
y2d = reshape(P, 365, []);
% Now extract 8 column vectors
y1 = y2d(1, :);
y2 = y2d(2, :);
y3 = y2d(3, :);
y4 = y2d(4, :);
y5 = y2d(5, :);
y6 = y2d(6, :);
y7 = y2d(7, :);
y8 = y2d(8, :);
If you don't know how many years there are in advance, you're advised to just leave y2d alone and use it as an array that you can index. For example if you're in a loop over k and you need the kth year
for k = 1 : size(y2d, 1)
thisYear = y2d(:, k); % Extract kth column (year)
% Now do something with the "thisYear" vector.
end
DON'T make separately named variables for reasons well explained in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
1 commentaire
Maria Fe
le 15 Juin 2017
Catégories
En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!