2

Coming from a numpy background I had to use Matlab for a new project started a few days ago.

Switching to Matlab was really straight forward since the syntax is somehow comparable to numpy's syntax. However, there is one thing I was not able to 'convert' in a satisfying way.

In numpy I am able to assign variables based on the rows of a array (or 'matrix' im Matlab terminology) like this:

import numpy as np

arr = np.array([1, 2, 3])
a, b, c = arr
print(a, b, c)

arr = np.array([[1, 2, 3],  [11, 22, 33]])
for row in arr:
    a, b, c = row
    print(a, b, c)

Which seems to quite elegant. However I did not find a eqivalent way to do this in Matlab without accessing each element of the matrix using index-notation.

Is there a equivalent way to perform variable assignment as shown in the second part of my Python snippet in Matlab or do I have to use the explicit index-notation?

1 Answer 1

2

The only way to really do this in MATLAB is to use a comma-separated list to "distribute" the contents of a cell array to multiple variables. The down-side is that it requires that you first convert your row (a numeric array) to a cell array using something like num2cell.

% Create an example numeric array
data = [1, 2, 3];

% Convert your data to a cell array
data_as_cell = num2cell(data);

% Use {:} indexing to convert the cell into a comma-separated list
[a, b, c] = data_as_cell{:};
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.