Clear Filters
Clear Filters

How to add rows to a mtrix following a certain condition?

1 view (last 30 days)
Suppose the following matrix r= [0; 1; 1.5; 1.6; 2; 10.4; 15.5].
How to add rows which are in the interval floor(r):0.1:floor(r)+1?
In the end, the output should be:
r_out = [0; 0.1; 0.2; ...; 1; 1.1; 1.2; ...; 2; 2.1; ...; 3; 10; 10.1; ...; 11; 15; 15.1; 15.2 ; ...; 16]
I have tried the following:
for i=1:size(r,1); p = floor(r(i)):0.1:floor(r(i))+1; q = [r; p']; end
However, it does not cover all the elements. Probably, the loop is erasing previous computation after each update.
  3 Comments
Anderson
Anderson on 26 Apr 2016
Edited: Anderson on 26 Apr 2016
No, this is absolutely not a homework!
I have tried the following:
for i=1:size(r,1); p = floor(r(i)):0.1:floor(r(i))+1; q = [r; p']; end
However, it does not cover all the elements. Probably, the loop is erasing previous computation after each update.
Anderson
Anderson on 26 Apr 2016
I found the problem.
r=unique(r, 'rows', 'stable');
for i=1:size(r,1); p(i,:) = floor(r(i)):0.1:floor(r(i))+1; end
q = unique(reshape(p,[],1));

Sign in to comment.

Answers (2)

Fangjun Jiang
Fangjun Jiang on 26 Apr 2016
r= [0; 1; 1.5; 1.6; 2; 10.4; 15.5];
rf=unique(floor(r));
r_out=bsxfun(@plus,rf.',(0:0.1:1).');
r_out=r_out(:);
The output is slightly different than what you listed. The difference is the elements of [2:0.1:3]. Not sure which one should be correct based on your post.

Anderson
Anderson on 26 Apr 2016
I found the problem.
r=unique(r, 'rows', 'stable');
for i=1:size(r,1); p(i,:) = floor(r(i)):0.1:floor(r(i))+1; end
q = unique(reshape(p,[],1));

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!