سؤال

I am trying to convert the following code in MATLAB to Python.

y = data(1:60000,6);
b = zeros(size(y));
for i = 1:size(y,1),
  ymean = mean(y(i,:));
  y(i,:) = y(i,:) - ymean;

I would appreciate any help with converting the code.

These is the code I developed till now,

b = zeros(size(z)) 
for i in range(1,size(z)): 
    ymean = numpy.mean(y(i,:)) 
    y(i,:) = y(i,:) - ymean
هل كانت مفيدة؟

المحلول

Welcome to python!

In python, we like code to be simple, succinct, and performant. Especially when using numpy, you should break the for loop model you may be used to thinking of in other languages.

Also we have indexing from 0, like the vast majority of languages. Rather than asking us to translate MATLAB code, most of the community would probably be more appreciative if you first explained the problem you were trying to solve.

Lucky for you, numpy is beautiful, and I have a large urge to show you how much simpler that code you wrote above can be. Specifically, you are subtracting the mean of each column from each element in that column.

Watch how easy this is:

centered_matrix = numpy.subtract(y, numpy.mean(y, axis=0)) 

Did you catch that? In numpy, you really shouldn't ever have to use a for loop. You can just say what you mean and it works beautifully. Here's hoping you never have to go back to MATLAB again.

Let me know if you have any questions.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top