Reputation: 2411
I have converted my training data matrix into z-scores for each column. I have mu
and sigma
for each column from the output of zscore
.
I also have another matrix (my test data) and I want to convert it into z-scores using the mu
and sigma
obtained in previous the step. My implementation uses for
loops as shown below:
TEST_DATA = zeros(num_rows,num_cols,'double');
for rowIdx = 1:num_rows,
for colIdx = 1:num_cols,
TEST_DATA(rowIdx,colIdx)=(input(rowIdx,colIdx)-MU(colIdx))/SIGMA(colIdx);
end
end
Is there any faster way of achieving this in MATLAB?
Upvotes: 1
Views: 3133
Reputation: 9317
You can use bsxfun
:
%// Sample data
matrix = rand(10, 10);
testData = rand(10, 10);
%// Obtain mu and sigma
mu = mean(matrix, 1);
sigma = std(matrix, [], 1);
%// or use: [Z, mu, sigma] = zscore(matrix);
%// Convert into z-scores using precalculated mu and sigma
C = bsxfun(@rdivide, bsxfun(@minus, testData, mu), sigma);
Upvotes: 2
Reputation: 14947
The documentation of zscore explains that it simply subtracts the mean and divides by the standard deviation. The only tricky part is apply the vectors of mu/sigma to each column. But if you don't know how to do the fancy way, do it with a for loop. I'll leave it this way for readability. If you need faster, look into bsxfun
.
for ii=1:size(mat,1)
mat(ii,:) = (mat(ii,:) - mu) ./ sigma;
end
Upvotes: 0