0

I would use programming-quote like this in Bash

$ export b=`ls /`
$ echo $b
Applications Library Network System Users Volumes tmp usr var

and now I want to find similar functionality in Matlab. Also, I want to find a command that outputs relative paths, not absolute paths like Matlab's ls -- I feel like reinventing the wheel if I am parsing this with a regex. I need to find this command to debug what is wrong with namespaces here. Familiar-Bash-style functionatilities would be so cool.

Community
  • 1
  • 1
hhh
  • 50,788
  • 62
  • 179
  • 282

2 Answers2

2

For your first question, I think you can get that behavior with anonymous functions:

b = @() ls('C:\');  %I'm on windows
b()

The expression b() now returns the contents of my C drive.

Pursuit
  • 12,285
  • 1
  • 25
  • 41
  • Anonymous functions rock! A bit like Python's list comprehension -- and someone said that you cannot do functions without a file in matlab so wrong XD Thank you for sharing +1, so powerful tool! – hhh Apr 11 '13 at 20:52
  • Hey, do you know how can I get files with anonymous function? `a=ls('.');b=@() if isequal(a.isdir,0) a.name end` (I know I am reinventing the wheel but good learning...). It would be so cool if something like this worked, `a.isdir*a.name` -- there must be some very elegant way... – hhh Apr 11 '13 at 20:57
  • This needs to be another question or it will get lost. – Pursuit Apr 11 '13 at 22:28
2

The Matlab equivalent of bash backticks is calling the system() function and using the second output argument. It will run an external command and capture the output.

[status,b] = system('ls /');

If it's a string of Matlab code you want to run and capture the console output of, use evalc.

But to just get a listing of files, you want the Matlab dir function. Lots easier than parsing that output string, and you get more info. See Matlab dir documentation or doc dir for more details.

children = dir('/');
childNames = { children.name };
childIsDir = [ children.isdir ];
Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
  • A problem with `children.name`, it contains also directories -- a flag to get only files like `"find . -type d"`? – hhh Apr 11 '13 at 20:39
  • There's also an `isdir` field in the `dir` output; you can use that to filter out the directories. – Andrew Janke Apr 11 '13 at 21:35