DonCorleoneM
DonCorleoneM

Reputation: 25

Duplicate table value to have the same size

I have two tables of different size. I'm using Matlab, it doesn't matter I just need the logic of doing this

the first table contains 8 elements the second one contains 3

0.04     0.1
0.08     0.2
0.12     0.3
0.16
0.20
0.24
0.28
0.32

I want to compare the two tables, repeating same value in the second table while tab1(i) < tab2(i) in order to get two tables of the same size the result must be like this

0.04     0.1
0.08     0.1
0.12     0.2
0.16     0.2
0.20     0.2
0.24     0.3
0.28     0.3
0.32     0.0

i've tried this

for ii=1:sizex1(1)
    for jj=1:ssimagefile
        if x2imagefile(jj)<=z1(ii)
            tab2(ii)=z1(ii)
            fprintf(file, '%f %f \n', [ii tab2]');
            jj=jj+1;
        else
            ii=ii+1;
        end
    end

Upvotes: 1

Views: 48

Answers (2)

josoler
josoler

Reputation: 1423

You could also take the following vectorized approach in case you prefer to avoid bsxfun:

tab2_sorted = sort(tab2);       % Sort tab2
tab3=zeros(size(tab1));         % Initialize the new table

% Fill the new table with the values of tab2
tab3(tab1<=tab2_sorted(3))=tab2_sorted(3);
tab3(tab1<=tab2_sorted(2))=tab2_sorted(2);
tab3(tab1<=tab2_sorted(1))=tab2_sorted(1);

Upvotes: 0

Dan
Dan

Reputation: 45752

Here is a Matlaby way to do it:

%// Add zeros to the end of tab2 so that it is as long as tab1
tab3(numel(tab1)) = 0;
%// use bsxfun to find for each number, which rows it will be replicated into
I = bsxfun(@le, tab1, tab2') & bsxfun(@gt, tab1, [-inf,tab2(1:end-1)']);
%// use find to convert the rows from the step before to indexes of where the numbers lie in tab1
[~,c] = find(I);
%// populate tab3 with the repeated numbers from tab2
tab3(1:numel(c)) = tab2(c);

And a simpler way using for loops:

tab3 = zeros(size(tab1));
for row = 1:numel(tab1)
    idx = tab2 > tab1(row);
    if any(idx)
        tab3(row) = min(tab2(idx));
    end
end

Upvotes: 2

Related Questions