[Solved] matlab Is there something like list comprehension as it is in python?

I am looking for something like list comprehensions in matlab however I couldnt find anything like this in the documentary.

In python it would be something like

A=[i/50 for i in range(50)]
Enquirer: bios

||

Solution #1:

Matlab is very fond of ‘vectorizing’. You would write your example as:

A = (0:49) ./ 50

Matlab hates loops and therefore list comprehension. That said, take a look at the arrayfun function.

Respondent: Marijn van Vliet

Solution #2:

You can do:

(1:50)/50

Or for something more general, you can do:

[email protected](x) (x/50);
arrayfun(f,1:50)
Respondent: Oli

Solution #3:

No, Matlab does not have list comprehensions. You really don’t need it, as the focus should be on array-level computations:

A = (1:50) / 50
Respondent: Michael J. Barber

Solution #4:

Matlab can work with arrays directly, making list comprehension less useful

Respondent: hc-song

Solution #5:

If what you’re trying to do is as trivial as the sample, you could simply do a scalar divide:

A = (0:50) ./ 50
Respondent: clokep

Solution #6:

There are several ways to generate a list in Matlab that goes from 0 to 49/50 in increments of 1/50

A = (0:49)/50

B = 0:1/50:49/50

C = linspace(0,49/50,50)

EDIT As Sam Roberts pointed out in the comments, even though all of these lists should be equivalent, the numerical results are different due to floating-point errors. For example:

max(abs(A-B))
ans =
   1.1102e-16
Respondent: Jonas

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.