0

I've been stuck on a MATLAB coding problem where I needed to create market weights for many stocks from a large data file with multiple days and portfolios.

I received help from an expert the other day using 'nested loops' it worked, but I don't understand what he has done in the final line. I was wondering if anyone could shed some light and provide an explanation of the last coding line. xp = x (where x = market value)

dates=unique(x(:,1)); (finds the unique dates in the data set Dates are column 1)
for i=1:size(dates,1) (creates an empty matrix to fill the data in)
   for j=5:size(xp,2)
     xp(xp(:,1)==dates(i),j)=xp(xp(:,1)==dates(i),j)./sum(xp(xp(:,1)==dates(i),j));    (help???)
   end
end

Any comment are much appreciated!

1 Answer 1

1

To understand the code, you have to understand the colon operator, logical indexing and the difference between / and ./. If any of these is unclear, please look it up in the documentation.

The following code does the same, but is easier to read because I separated each step into a single line:

dates=unique(x(:,1));
%iterates over all dates. size(dates,1) returns the number of dates
for i=1:size(dates,1)
   %iterates over the fifth to last column, which contains the data that will be normalised.
   for j=5:size(xp,2)
     %mdate is a logical vector, which is used to select the rows with the currently processed date.
     mdate=(xp(:,1)==dates(i))
     %s is the sums up all values in column j same date
     s=sum(xp(mdate,j))
     %divide all values in column j with the same date by s, which normalises to 1
     xp(mdate,j)=xp(mdate,j)./s;
   end
end

With this code, I suggest to use the debugger and step through the code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.