Matt Ellen
Matt Ellen

Reputation: 11592

How can I append values to a 2D array?

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.

Upvotes: 1

Views: 217

Answers (2)

gnovice
gnovice

Reputation: 125864

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.

Upvotes: 2

yuk
yuk

Reputation: 19870

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];

Upvotes: 2

Related Questions