EzDevInfo.com

matlab interview questions

Top matlab frequently asked interview questions

Octave / Matlab: Extend a vector making it repeat itself?

Is there a way to extend a vector by making it repeat itself?

>v = [1 2];
>v10 = v x 5; %x represents some function. Something like "1 2" x 5 in perl

Then v10 would be:

>v10
     1 2 1 2 1 2 1 2 1 2

This should work for the general case, not just for [1 2]


Source: (StackOverflow)

In MATLAB, can I have a script and a function definition in the same file?

Suppose I have a function f() and I want to use it in my_file.m, which is a script.

  1. Is it possible to have the function defined in my_file.m?
  2. If not, suppose I have it defined in f.m. How do I call it in my_file.m?

I read the online documentation, but it wasn't clear what is the best way to do this.


Source: (StackOverflow)

Advertisements

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Is there a foreach structure in MATLAB? If so, what happens if the underlying data changes (i.e. if objects are added to the set)?


Source: (StackOverflow)

Default Arguments in Matlab

Is it possible to have default arguments in Matlab? For instance, here:

function wave(a,b,n,k,T,f,flag,fTrue=inline('0'))

I would like to have the true solution be an optional argument to the wave function. If it is possible, can anyone demonstrate the proper way to do this? Currently, I am trying what I posted above and I get:

??? Error: File: wave.m Line: 1 Column: 37
The expression to the left of the equals sign is not a valid target for an assignment.

Thanks!


Source: (StackOverflow)

How to visualize a project structure in MATLAB? [closed]

I've come into ownership of several thousand lines of Matlab code, some as >900 line functions and a few directories full of function_name.m files. It's hard to figure out what everything is doing (or relating to) or figure out the dependencies. What would you suggest to visualize the functions structure, such as what functions are called from which, and in what sequence?


Source: (StackOverflow)

Is it possible to define more than one function per file in MATLAB?

When I was studying for my undergraduate degree in EE, MATLAB required each function to be defined in its own file, even if it was a one-liner.

I'm studying for a graduate degree now, and I have to write a project in MATLAB. Is this still a requirement for newer versions of MATLAB?

If it is possible to put more than one function in a file, are there any restrictions to this? For instance, can all the functions in the file be accessed from outside the file, or only the function that has the same name as the file?

Note: I am using MATLAB release R2007b.


Source: (StackOverflow)

Read .mat files in Python

Does anyone have successful experience reading binary Matlab .mat files in Python?

(I've seen that scipy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed scipy version 0.7.0, and I can't find the loadmat() method)


Source: (StackOverflow)

Accelerating MATLAB code using GPUs?

AccelerEyes announced in December 2012 that it works with Mathworks on the GPU code and has discontinued its product Jacket for MATLAB:

http://blog.accelereyes.com/blog/2012/12/12/exciting-updates-from-accelereyes/

Unfortunately they do not sell Jacket licences anymore.

As far as I understand, the Jacket GPU Array solution based on ArrayFire was much faster than the gpuArray solution provided by MATLAB.

I started working with gpuArray, but I see that many functions are implemented poorly. For example a simple

myArray(:) = 0 

is very slow. I have written some custom CUDA-Kernels, but the poorly-implemented standard MATLAB functionality adds a lot of overhead, even if working with gpuArrays consistently throughout the code. I fixed some issues by replacing MATLAB code with hand written CUDA code - but I do not want to reimplement the MATLAB standard functionality.

Another feature I am missing is sparse GPU matrices.

So my questions are:

How do is speed up the badly implemented default GPU implementations provided by MATLAB? In particular, how do I speed up sparse matrix operations in MATLAB using the GPU?


Source: (StackOverflow)

MatLab error: cannot open with static TLS

Since a couple of days, I constantly receive the same error while using MATLAB which happens at some point with dlopen. I am pretty new to MATLAB, and that is why I don't know what to do. Google doesn't seem to be helping me either. When I try to make an eigenvector, I get this:

Error using eig
LAPACK loading error:
dlopen: cannot load any more object with static TLS

I also get this while making a multiplication:

Error using  * 
BLAS loading error:
dlopen: cannot load any more object with static TLS

I did of course look for the solutions to this problem, but I don't understand too much and don't know what to do. These are threads I found:

  1. How do I use the BLAS library provided by MATLAB?
  2. http://www.mathworks.de/de/help/matlab/matlab_external/calling-lapack-and-blas-functions-from-mex-files.html

Can someone help me please?

Examples of function calls demonstrating this error

>> randn(3,3)

ans =

 2.7694    0.7254   -0.2050             
-1.3499   -0.0631   -0.1241             
 3.0349    0.7147    1.4897            

>> eig(ans)

Error using eig
LAPACK loading error:
dlopen: cannot load any more object with static TLS

Source: (StackOverflow)

A tool to convert MATLAB code to Python [closed]

I have a bunch of MATLAB code from my MS thesis which I now want to convert to Python (using numpy/scipy and matplotlib) and distribute as open-source. I know the similarity between MATLAB and Python scientific libraries, and converting them manually will be not more than a fortnight (provided that I work towards it every day for some time). I was wondering if there was already any tool available which can do the conversion.


Source: (StackOverflow)

Setting graph figure size

All I want to do is make the width greater and the height smaller. I'm just doing raster plots but this question applies to any MATLAB figure. I can manually resize it using the figure directly when it's created but I want the program to spit it out in the right size to start with.


Source: (StackOverflow)

arrayfun can be significantly slower than an explicit loop in matlab. Why?

Consider the following simple speed test for arrayfun:

T = 4000;
N = 500;
x = randn(T, N);
Func1 = @(a) (3*a^2 + 2*a - 1);

tic
Soln1 = ones(T, N);
for t = 1:T
    for n = 1:N
        Soln1(t, n) = Func1(x(t, n));
    end
end
toc

tic
Soln2 = arrayfun(Func1, x);
toc

On my machine (Matlab 2011b on Linux Mint 12), the output of this test is:

Elapsed time is 1.020689 seconds.
Elapsed time is 9.248388 seconds.

What the?!? arrayfun, while admittedly a cleaner looking solution, is an order of magnitude slower. What is going on here?

Further, I did a similar style of test for cellfun and found it to be about 3 times slower than an explicit loop. Again, this result is the opposite of what I expected.

My question is: Why are arrayfun and cellfun so much slower? And given this, are there any good reasons to use them (other than to make the code look good)?

Note: I'm talking about the standard version of arrayfun here, NOT the GPU version from the parallel processing toolbox.

EDIT: Just to be clear, I'm aware that Func1 above can be vectorized as pointed out by Oli. I only chose it because it yields a simple speed test for the purposes of the actual question.

EDIT: Following the suggestion of grungetta, I re-did the test with feature accel off. The results are:

Elapsed time is 28.183422 seconds.
Elapsed time is 23.525251 seconds.

In other words, it would appear that a big part of the difference is that the JIT accelerator does a much better job of speeding up the explicit for loop than it does arrayfun. This seems odd to me, since arrayfun actually provides more information, ie, its use reveals that the order of the calls to Func1 do not matter. Also, I noted that whether the JIT accelerator is switched on or off, my system only ever uses one CPU...


Source: (StackOverflow)

Hash tables in MATLAB

Does MATLAB have any support for hash tables?


Some background

I am working on a problem in Matlab that requires a scale-space representation of an image. To do this I create a 2-D Gaussian filter with variance sigma*s^k for k in some range., and then I use each one in turn to filter the image. Now, I want some sort of mapping from k to the filtered image.

If k were always an integer, I'd simply create a 3D array such that:

arr[k] = <image filtered with k-th guassian>

However, k is not necessarily an integer, so I can't do this. What I thought of doing was keeping an array of ks such that:

arr[find(array_of_ks_ = k)] = <image filtered with k-th guassian>

Which seems pretty good at first thought, except I will be doing this lookup potentially a few thousand times with about 20 or 30 values of k, and I fear that this will hurt performance.

I wonder if I wouldn't be better served doing this with a hash table of some sort so that I would have a lookup time that is O(1) instead of O(n).


Now, I know that I shouldn't optimize prematurely, and I may not have this problem at all, but remember, this is just the background, and there may be cases where this is really the best solution, regardless of whether it is the best solution for my problem.


Source: (StackOverflow)

In Matlab, when is it optimal to use bsxfun?

My Question: I've noticed that a lot of good answers to Matlab questions on SO frequently use the function bsxfun. Why?

Motivation: In the Matlab documentation for bsxfun, the following example is provided:

A = magic(5);
A = bsxfun(@minus, A, mean(A))

Of course we could do the same operation using:

A = A - (ones(size(A, 1), 1) * mean(A));

And in fact a simple speed test demonstrates the second method is about 20% faster. So why use the first method? I'm guessing there are some circumstances where using bsxfun will be much faster than the "manual" approach. I'd be really interested in seeing an example of such a situation and an explanation as to why it is faster.

Also, one final element to this question, again from the Matlab documentation for bsxfun: "C = bsxfun(fun,A,B) applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled.". What does the phrase "with singleton expansion enabled" mean?


Source: (StackOverflow)

Automatically plot different colored lines

I'm trying to plot several kernel density estimations on the same graph, and I want them to all be different colors. I have a kludged solution using a string 'rgbcmyk' and stepping through it for each separate plot, but I start having duplicates after 7 iterations. Is there an easier/more efficient way to do this, and with more color options?

for n=1:10
 source(n).data=normrnd(rand()*100,abs(rand()*50),100,1); %generate random data
end
cstring='rgbcmyk'; % color string
figure
hold on
for n=1:length(source)
 [f,x]=ksdensity(source(n).data); % calculate the distribution
 plot(x,f,cstring(mod(n,7)+1))  % plot with a different color each time
end

Source: (StackOverflow)