Skip to content

Instantly share code, notes, and snippets.

@adambard
Created May 3, 2012 23:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adambard/2590371 to your computer and use it in GitHub Desktop.
Save adambard/2590371 to your computer and use it in GitHub Desktop.
Stupid MATLAB Tricks.
function stupid_tricks
% I made some functional tools for MATLAB.
assert(reduce_(@(x, y) x + y, [1, 2, 3, 4]) == 10)
% They got a little out of hand.
join = @(sep, args) ...
if_(ischar(sep), @() ... % Input check
reduce_(@(x, y) [x sep y], ... % Reduce to string
map_(@num2str, args))); % Convert args to string.
assert(strcmp(join(', ', {1, 2, 3, 4}), '1, 2, 3, 4'));
% And then they just got ridiculous.
tail = @(lst) lst(2:end);
head = @(lst) lst(1);
qs = Y(@(self) @(lst) ...
if_(isempty(lst), ...
@() [], ... # Is empty
@() [...
self(tail(lst(lst <= head(lst))))
head(lst)
self(lst(lst > head(lst)))]));
assert(all(qs([8,2,45,0,4,1,2,3]) == [0, 1, 2, 2, 3, 4, 8, 45]'));
end
%%%%%%%%% Functions %%%%%%%%%%%%%%%
function retval = apply(fn, args)
if isnumeric(args)
args = num2cell(args);
end
retval = fn(args{:});
end
function retval = map_(fn, args)
was_numeric = isnumeric(args);
if was_numeric
args = num2cell(args);
end
retval = cellfun(fn, args, 'UniformOutput', false);
end
function retval = reduce_(fn, vals, varargin)
if ~iscell(vals)
vals = num2cell(vals);
end
if nargin > 2
retval = varargin{1};
start = 1;
else
retval = fn(vals{1}, vals{2});
start = 3;
end
for ii=start:length(vals)
retval = fn(retval, vals{ii});
end
end
function retval = if_(predicate, if_fn, else_fn)
if predicate
retval = if_fn();
else
retval = else_fn();
end
end
function res = Y(f)
res = apply(...
@(x) f(@(y) apply(apply(x, {x}), {y})), ...
{@(x) f(@(y) apply(apply(x, {x}), {y}))});
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment