How to separate groups of numbers between NaN in new variables?
2 views (last 30 days)
Show older comments
Hello everyone, I have a vector similar to this:
v = [NaN NaN 1 2 3 4 5 NaN NaN 6 7 8 9 10 NaN NaN NaN NaN 11 12 13 14 15 16 17 18 NaN NaN]
I would like to separate the sets of numbers into new variables. Then it would look like this:
v1 = [1 2 3 4 5]
v2 = [6 7 8 9 10]
v3 = [11 12 13 14 15 16 17 18]
I thought a lot about how to do this but I could not, I could do it manually, but it's a lot of numbers and it would be very hard work. So I decided to ask here. If anyone can help me, I will be very grateful.
1 Comment
Stephen23
on 25 May 2018
Edited: Stephen23
on 25 May 2018
@Robson Passos: creating numbered variables like this is a sign that you are doing something wrong. Rather than creating pseudo indices you would be much better off turning them into real indices: real indices will be simpler, more efficient, less buggy, and easier to debug. Read this to know why:
Accepted Answer
Image Analyst
on 24 May 2018
If you have the Image Processing Toolbox, it's trivial - just one lines of code (a call to regionprops):
v = [NaN NaN 1 2 3 4 5 NaN NaN 6 7 8 9 10 NaN NaN NaN NaN 11 12 13 14 15 16 17 18 NaN NaN]
props = regionprops(~isnan(v), v, 'PixelValues')
% Now you're done. Results are in the props structure array.
% To show you , print them out:
for k = 1 : length(props)
fprintf('Values in region #%d = ', k);
fprintf('%d ', props(k).PixelValues);
fprintf('\n'); % Go to new line.
end
In the command window you'll see:
props =
3×1 struct array with fields:
PixelValues
Values in region #1 = 1 2 3 4 5
Values in region #2 = 6 7 8 9 10
Values in region #3 = 11 12 13 14 15 16 17 18
0 Comments
More Answers (1)
Stephen23
on 25 May 2018
Edited: Stephen23
on 25 May 2018
>> v = [NaN NaN 1 2 3 4 5 NaN NaN 6 7 8 9 10 NaN NaN NaN NaN 11 12 13 14 15 16 17 18 NaN NaN];
>> idd = diff([true,isnan(v),true]);
>> idb = find(idd<0);
>> ide = find(idd>0)-1;
>> out = arrayfun(@(b,e)v(b:e),idb,ide,'uni',0)
>> out{:}
ans =
1 2 3 4 5
ans =
6 7 8 9 10
ans =
11 12 13 14 15 16 17 18
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!