Divide matrix in to vectors using for-loop
Show older comments
So, i have a 12*X matrix where each row represents a month (jan-dec) and each column represents a year (could be any amount of years). I want to divide these into separate vectors of months and years using a for-loop.
This is my thought on how to do it but it doesnt work, basically i want to create variables for each year where y1 represents year 1, y2 represents year 2 and so on. I get a error message as soon as i try to run this and i think the problem is in the y(i) part which is supposed to make the different variables.
for i=1:length(x)
y(i)=x(:, i);
end
1 Comment
Guillaume
on 21 Sep 2017
Creating several variables from one matrix = a very bad idea.
In all likelyhood, even splitting the matrix into a cell array or similar is also a bad idea. If you're trying to obtain statistics per month/year/whatever keeping the data together in the matrix would be much simpler. Tools like findgroups and splitapply can let you get monthtly/annually/etc. stats.
Accepted Answer
More Answers (1)
Guillaume
on 22 Sep 2017
"The values in my matrix is the monthly developement of the stock market. My final result is a table displayed in the command window which shows the average developement for each month/year and it shall also mark the best and worst developement".
In which case, splitting the matrix is the wrong way to approach this:
%build demo table
date = datetime + (0:-4:-800)';
stock = randi([0 100], size(date));
dailystock = table(date, stock); %note that table is ordered here. It doesn't even have to be
%compute monthly average min and max:
[bin, bindates] = discretize(dailystock.date, 'month');
[daterow, ~, group] = unique(bin);
months = bindates(daterow)';
months.Format = 'MM/yyyy';
monthlystock = table(months, ...
splitapply(@mean, dailystock.stock, group), ...
splitapply(@max, dailystock.stock, group), ...
splitapply(@min, dailystock.stock, group), ...
'VariableNames', {'month', 'monthly_mean', 'monthly_max', 'monthly_min'})
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!