A.Torres
A.Torres

Reputation: 423

Arrays in Matlab/Python, indexing errors

I have been converting some Matlab code into Python. I have been debugging this program for a while and I am wondering if I am correct in the way I am thinking about the arrays in Matlab.

I have this code in Matlab (edited to add missing variables and executions):

pdf_pars = pdf_pars(1)*ones(1,p);
weights = 1;

% determine  the size of each lenght
mode_length = round(weights*samp_size);

% correct for rounding erros
mode_length(no_modes) = mode_length(no_modes) + samp_size - sum(mode_length) ;

for i=1:no_modes
    x = [x dirichlet(pdf_pars(i,:),mode_length(i))']; 
end 

When you read the first line, it seemed to me like mode_length was an integer (or perhaps a double). However the next line starts indexing. I know that in Python, this treatment of mode_length will cause an error.

Am I interpreting this Matlab code correctly? And how can I work around this as I continue moving code into Python?

Upvotes: 0

Views: 81

Answers (2)

rahlf23
rahlf23

Reputation: 9019

Without knowing what weights, samp_size, and no_modes are, this is somewhat speculative.

With that being said, round() in MATLAB will retain the size that is passed as an input. Therefore, if you pass a double, then it will round the double and return a double. Likewise, if you pass a vector, then MATLAB will perform the rounding element-wise and return a vector.

So assuming that weights is a vector and samp_size is a scalar, then you are applying round() to each element of the resulting vector from weights*samp_size, thus mode_length will be a vector.

Then it looks like you are modifying the element in mode_length that corresponds to index no_modes, and simply adding samp_size and subtracting sum(mode_length), both of which are scalar values.

Something to note if you are not aware: MATLAB indexing begins at 1, whereas Python indexing begins at 0.

Upvotes: 2

iacob
iacob

Reputation: 24341

round(X) in Matlab rounds each element of X. If you feed it a vector, it returns a vector.

Upvotes: 2

Related Questions