How to automatically create new variables from existing column vector?

2 views (last 30 days)
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.

Accepted Answer

John D'Errico
John D'Errico on 11 Jun 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.

More Answers (1)

Image Analyst
Image Analyst on 11 Jun 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

Categories

Find more on Data Type Identification in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!