merging two list into one and filling in missing values with [# 0]....

4 views (last 30 days)
Hello all, I have a qustion on how to merge some list. I also need to create new values if there not existing. I have something similar made with for loops, but it is a brute force method and is not working all the way. I was hoping for some help to make it better and more efficient code. So here is what I got:
%input:
list_all = [ 1.0000 0.0901; 2.0000 0.0920; 4.0000 0.0796; 5.0000 0.0752; 10.0000 0.0404];
%code:
for n = 1:10
h = ismember(list_all(:,1),n);
if sum(h) == 0
j(n,:) = [n 0];
else
j(n,:) = full_unique1(h,:);
end
end
j
Here is my output:
j =
1.0000 0.0901
2.0000 0.0920
3.0000 0
3.0000 0.0796 %this one is wrong
4.0000 0.0796
6.0000 0
7.0000 0
8.0000 0
9.0000 0
5.0000 0.0752 %this one is wrong too, missing 10
Also I was not sure how to get rid of the .0000 in column one. I would like the code to do an output of:
j =
1 0.0901
2 0.0920
3 0
4 0.0796
5 0.0752
6 0
7 0
8 0
9 0
10 0.0404
Any help is very appreciated!
Thank you,
Chris

Accepted Answer

Image Analyst
Image Analyst on 16 Dec 2012
You mean like this:
list_all = [ 1.0000 0.0901; 2.0000 0.0920; 4.0000 0.0796; 5.0000 0.0752; 10.0000 0.0404]
% Initialize an output array, list_all_2
maxRow = max(list_all(:,1))
list_all_2 = zeros(maxRow, 2)
list_all_2(:,1) = 1:maxRow
% Get original values
rows = list_all(:,1)
values = list_all(:, 2)
% Assign value in col 2 of output to the input's value.
list_all_2(rows, 2) = values
  3 Comments
Image Analyst
Image Analyst on 16 Dec 2012
Edited: Image Analyst on 16 Dec 2012
Print it out with sprintf() instead of just listing the variable name. You can specify however many decimal places you want. Or cast to int32 and use sprintf('%d', integerNumber).
sprintf('%d, %.3f\n', int32(list_all_2(rowNumber, 1)), list_all_2(rowNumber, 2));
If you want to find the last number in column2 and have it's row number be maxRow do it like this:
maxRow = find(list_all(:, 2), 1, 'last');
So it will ignore any zeros in rows beyond that. But whatever works for you...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!