How to automatically create new variables from existing column vector?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Maria Fe
le 11 Juin 2017
Modifié(e) : Stephen23
le 19 Juin 2019
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.
2 commentaires
Réponse acceptée
John D'Errico
le 11 Juin 2017
Don't do it! In fact, you don't actually NEED to do what you want.
Instead, learn how to use the various types of arrays in MATLAB, cell arrays, structs. You could even just do this using an index, that would indicate the data for each year.
But best? Just reshape the array.
Y = reshape(P,[365,5]);
If you want year 1?
Y(:,1)
How much easier is it to work with that? If you have 10 years worth of data, just change the reshape call. And now you can use loops and array operations on all of your data at once.
Creating and working with numbered variables will create unwieldy, unreadable, buggy code.
So save yourself the trouble. Instead, learn to use MATLAB properly.
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
Voir également
Catégories
En savoir plus sur Data Type Identification dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!