Update 2 (to answer your updated question)
MATLAB is optimized for working with arrays. Once you get used to it, it’s really nice to just type one line and MATLAB to do the whole 4D loop without worrying about it. MATLAB is often used for prototype / one-time calculations, so it makes sense to save time for human coding and abandon some C flexibility [++ | #].
This is why MATLAB internally does some loops really well - often by encoding them as a compiled function.
The code snippet you give doesn’t actually contain the corresponding line of code that does the bulk of the work, namely
% Sort along given dimension x = sort(x,dim);
In other words, the code you are showing requires only access to the median values at their correct index in the now sorted multidimensional array x
(which does not take much time). The actual work of accessing all elements of the array was done using sort
, which is a built-in (i.e., compiled and optimized) function.
Original answer (on how to create your own fast functions that work with arrays)
In fact, there are quite a few built-in modules that take a measurement parameter: min(stack, [], n)
, max(stack, [], n)
, mean(stack, n)
, std(stack, [], n)
, median(stack,n)
, sum(stack, n)
... while other built-in functions, such as exp()
, sin()
, automatically work on every element of your entire array (i.e. sin(stack)
automatically executes four nested loops for you if stack
is 4D), you can create many functions that you might need, just rely on existing built-in functions .
If this is not enough for a specific case, you should look at repmat
, bsxfun
, arrayfun
and accumarray
, which are very powerful functions for performing MATLAB path actions. Just do a SO search for questions (or rather answers) using one , I learned a lot about MATLABs strengths.
As an example , let's say you wanted to implement a p-norm stack of size n
, you can write
function result=pnorm(stack, p, n) result=sum(stack.^p,n)^(1/p);
... where you effectively reuse the "dimension" sum
.
Update
As Max points out in the comments, also see the colon operator ( :
, which is a very powerful tool for selecting elements from an array (or even changing its shape, which is more commonly done with reshape
).
In general, look in the Array Operations section in help - it contains repmat
et al. mentioned above, but also cumsum
and some more obscure auxiliary functions that you should use as building blocks.