bios
bios

Reputation: 1027

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)]

Upvotes: 10

Views: 10559

Answers (7)

Bill
Bill

Reputation: 11613

This doesn't work help with your numerical example but for the special case of strings there is the compose function that does the same thing as a list comprehension of the form:

s = [f"Label_{i}" for i in range(1, 6)]

Example:

str = compose("Label_%d", 1:5)

Result:


str = 

  1×5 string array

    "Label_1"    "Label_2"    "Label_3"    "Label_4"    "Label_5"

Upvotes: 0

Jonas
Jonas

Reputation: 74940

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

Upvotes: 0

Oli
Oli

Reputation: 16045

You can do:

(1:50)/50

Or for something more general, you can do:

f=@(x) (x/50);
arrayfun(f,1:50)

Upvotes: 6

clokep
clokep

Reputation: 140

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

A = (0:50) ./ 50

Upvotes: 0

Marijn van Vliet
Marijn van Vliet

Reputation: 5399

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.

Upvotes: 13

hc-song
hc-song

Reputation: 99

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

Upvotes: 0

Michael J. Barber
Michael J. Barber

Reputation: 25042

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

Upvotes: 2

Related Questions