List comprehensions vs. functions

9 visualizaciones (últimos 30 días)
Jordan May
Jordan May el 2 de Mzo. de 2021
Comentada: Jordan May el 2 de Mzo. de 2021
Hi, I am new to MATLAB and I am trying to recreate some python code in MATLAB and was wondering if there is anything like this I would be able to do in MATLAB to make life a little easier.
[(-1)**b*0.2*(b+0.1) for b in range(-30,31) if b>5 or b<-5]
Would I be able to do this, or would I need to create a function to do this for me? Thanks for any help in advance.
  2 comentarios
Stephen23
Stephen23 el 2 de Mzo. de 2021
Editada: Stephen23 el 2 de Mzo. de 2021
MATLAB does not have list comprehensions.
List comprehansions are fundamentally just syntatic sugar for loops, so it is not clear how or why you think a function would be necessary. At first glance, some basic indexing applied to matrices would perform the same purpose:
Jordan May
Jordan May el 2 de Mzo. de 2021
Thank you. I used the for loop, and realised using functions was just ridiculous and got the code to replicate the python. Except it seems to runs 60x faster on Matlab, so I am very happy with the result. Thank you again.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 2 de Mzo. de 2021
Editada: Stephen23 el 2 de Mzo. de 2021
b = -30:30;
b = b(b<-5|b>5);
v = (-1).^b .* 0.2 .* (b+0.1)
v = 1×50
-5.9800 5.7800 -5.5800 5.3800 -5.1800 4.9800 -4.7800 4.5800 -4.3800 4.1800 -3.9800 3.7800 -3.5800 3.3800 -3.1800 2.9800 -2.7800 2.5800 -2.3800 2.1800 -1.9800 1.7800 -1.5800 1.3800 -1.1800 1.2200 -1.4200 1.6200 -1.8200 2.0200
Python output:
%[-5.98, 5.78, -5.58, 5.38, -5.18, 4.98, -4.78, 4.58, -4.38, 4.18, -3.98, 3.78, -3.58, 3.38, -3.18, 2.9800000000000004, -2.7800000000000002, 2.58, -2.3800000000000003, 2.18, -1.9800000000000002, 1.7800000000000002, -1.58, 1.3800000000000001, -1.1800000000000002, 1.22, -1.42, 1.62, -1.82, 2.02, -2.22, 2.42, -2.62, 2.8200000000000003, -3.02, 3.2200000000000006, -3.4200000000000004, 3.6200000000000006, -3.8200000000000003, 4.0200000000000005, -4.220000000000001, 4.420000000000001, -4.62, 4.82, -5.0200000000000005, 5.220000000000001, -5.420000000000001, 5.620000000000001, -5.82, 6.0200000000000005]

Más respuestas (0)

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by