albert - 19 days ago 4x

Python Question

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?

Answer

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{:};
```

Source (Stackoverflow)

Comments