views:

67

answers:

2

I am new to MATLAB, and I can't fathom this from the documentation.

function GotData(sender, args)
    interval = args.DataBlock.TimeIntervalInMicroseconds;
    doubles = args.DataBlock.AsDoubleArray();
    x = 0;
    complexCount = length(double(doubles))/2;
    DATA = zeros(complexCount);
    for index = 1:(complexCount-1)
        realnum = doubles(2 * index);
        imagnum = 1i * doubles(2 * index + 1);
        complex = realnum + imagnum;
        x = x + interval;
        DATA(index) = [x complex];
    end
    disp(DATA)
end

I am getting an array of doubles from an event that fires in a .NET assembly. I'm splitting the array up so that each even item (in a 1 based array) is an imaginary number and each odd item is real. Then I create a two item array of the complex number and its interval. I want to then append this 1D array to a 2D array. How do I do that?

At the moment I'm getting an error: In an assignment A(I) = B, the number of elements in B and I must be the same.. What should I be doing?

interval is 1, but can be adjusted.

+2  A: 

If you want DATA to be a 2-D array, you need to initialize it and index it as such:

%# ...(your code)...
DATA = zeros(complexCount-1,2);   %# Initialize DATA to an N-by-2 matrix
%# ...(your code)...
    DATA(index,:) = [x complex];  %# Add the array to a row of DATA
%# ...(your code)...

You can check out these MathWorks documentation links for further information about creating matrices and matrix indexing in MATLAB.

gnovice
That's exactly what I needed. Thanks, @gnovice.
Matt Ellen
+2  A: 

I was writing the same answer as gnovice, but he fired first. :)

In addition, if real data correspond to odd items and imaginary to even items, you should change the assignments:

realnum = doubles(2 * index - 1);
imagnum = 1i * doubles(2 * index);

Anyway I would vectorize the code to avoid for-loop:

%# ... code to get doubles and interval variables
n = numel(doubles);
realnum = doubles(1:2:n)';
imagnum = 1i * doubles(2:2:n)';
x = interval.*(1:numel(realnum)).';
DATA = [x realnum + imagnum];
yuk
Good point about vectorizing, but I think `interval` is a single value, not an array.
gnovice
@gnovice, You are right, I just updated.
yuk
Actually, `x = interval.*(1:numel(realnum)).';` should suffice. ;)
gnovice
Yeh, you are right. Will correct.
yuk
Thanks, @yuk. MatLab is a different language to what I'm used to!
Matt Ellen
@yuk: You need to make the `realnum` and `imagnum` arrays into column arrays, otherwise matlab complains that CAT arguments dimensions are not consistent.
Matt Ellen
Right, updated.
yuk