0

This program has to standardise data from 'LoadLargeDataSetGranese' (it's a dataset). I have to compare different variables in the same dataset.

That's my error: Index in position 2 exceeds array bounds. Index must not exceed 114. Error in factormodel2 (line 10) Xs(:,i) = (X(:,i) - mean(X(:,i)))/std(X(:,i)); % subtract the mean and divide by std

LoadLargeDataSetGranese

% standardize data
[n,p] = size(X); % number of time observations and variables
Xs = zeros(n,p); % not necessary, but useful for speed
i = 1;
for i = 1:n % loop on variables
    i = i + 1;
Xs(:,i) = (X(:,i) - mean(X(:,i)))/std(X(:,i)); % subtract the mean and divide by std
end

% estimate the factors, the factor loadings, the common components
% and the spectral decomposition
[Z, Phi, lambda, chi, R2, SDec] = principalcomponents(Xs, 11);


ExplainedV = 100*cumsum(SDec([1 21 22 37 50 73],:),2);
  • You have `i = 1` and `i = i + 1`. What do you think `for i = 1:n` does? And even then you'd start the loop from 2 and end with `end + 1`, which should explain the very clear error message. – Andras Deak -- Слава Україні Apr 29 '23 at 12:48
  • Does this answer your question? [What's the best way to iterate through columns of a matrix?](https://stackoverflow.com/questions/216341/whats-the-best-way-to-iterate-through-columns-of-a-matrix) – Andras Deak -- Слава Україні Apr 29 '23 at 12:50
  • you are looping over the 2nd dimension (column) of X, which has a length of p, instead, your for-loop uses n which is the dimension of the first dimension. – FangQ Apr 29 '23 at 13:57
  • 1
    also, use vector operations (i.e. commands that operate on entire matrix or row/columns) in matlab whenever possible. in many cases, it can be much faster than using for-loops. In this case, you can simply use `Xs =(X-mean(X))./std(X);` or `Xs =(X-repmat(mean(X),size(X,1),1))./repmat(std(X),size(X,1),1);` (for older MATLAB) to achieve the entire for loop. – FangQ Apr 29 '23 at 14:02

0 Answers0