YLM
YLM

Reputation: 345

save vectors of different sizes in matrix

I would like to divide a vector in many vectors and put all of them in a matrix. I got this error "Subscripted assignment dimension mismatch."

STEP = zeros(50,1);
STEPS = zeros(50,length(locate));
for i = 1:(length(locate)-1)
    STEP = filtered(locate(i):locate(i+1));
    STEPS(:,i) = STEP;
end

I take the value of "filtered" from (1:50) at the first time for example and I would like to stock it in the first row of a matrix, then for iterations 2, I take value of "filtered from(50:70) for example and I stock it in row 2 in the matrix, and this until the end of the loop..

If someone has an idea, I don't get it! Thank you!

Upvotes: 3

Views: 263

Answers (1)

Divakar
Divakar

Reputation: 221574

As mentioned in the comments, to make it work you can edit the loopy code at the end with -

STEPS(1:numel(STEP),i) = STEP;

Also, output array STEPS doesn't seem to use the last column. So, the initialization could use one less column, like so -

STEPS = zeros(50,length(locate)-1);

All is good with the loopy code, but in the long run with a high level language like MATLAB, you might want to look for faster codes and one way to achieve that would be vectorized codes. So, let me suggest a vectorized solution using bsxfun's masking capability to process such ragged-arrays. The implementation to cover generic elements in locate would look something like this -

% Get differentiation, which represent the interval lengths for each col
diffs = diff(locate)+1;

% Initialize output array
out = zeros(max(diffs),length(locate)-1);

% Get elements from filtered array for setting into o/p array
vals = filtered(sort([locate(1):locate(end) locate(2:end-1)]));

% Use bsxfun to create a mask that are to be set in o/p array and set thereafter
out(bsxfun(@ge,diffs,(1:max(diffs)).')) = vals;

Sample run for verification -

>> % Inputs
locate = [6,50,70,82];
filtered = randi(9,1,120);

% Get extent of output array for number of rows
N = max(diff(locate))+1;

>> % Original code with corrections
STEP = zeros(N,1);
STEPS = zeros(N,length(locate)-1);
for i = 1:(length(locate)-1)
    STEP = filtered(locate(i):locate(i+1));
    STEPS(1:numel(STEP),i) = STEP;
end

>> % Proposed code
diffs = diff(locate)+1;
out = zeros(max(diffs),length(locate)-1);
vals = filtered(sort([locate(1):locate(end) locate(2:end-1)]));
out(bsxfun(@ge,diffs,(1:max(diffs)).')) = vals;

>> max_error = max(abs(out(:)-STEPS(:)))
max_error =
     0

Upvotes: 2

Related Questions