How can I get the number between 2 numbers?

3 次查看(过去 30 天)
I have 2 arrays and the index of the stable numbers(n)
n=[1 2 7 9];
PA = [1 3 10 1 2 8 6 2 7 11 7 9 5 9];
PB = [1 10 1 2 11 6 2 7 3 7 9 5 8 9];
I want to store those numbers between the couple same numbers( 1 1, 2 2, 7 7, 9 9) separately in the cell like below.
CA={[3 10];[8 6];[11];[5]};
CB={[10];[11 6];[3];[5 8]};

采纳的回答

dpb
dpb 2019-5-12
ix=cell2mat(arrayfun(@(n)find(PA==n),n,'uni',0).');
PA=arrayfun(@(i1,i2)PA(i1+1:i2-1),ix(:,1),ix(:,2),'uni',0);
PB should be obvious... :)
Not using two named variables if the number elements is always the same could let write more generic code...or a cell array for them as well if different. If the A, B suffixes are significant, the row or cell index would be the identifier.

更多回答(1 个)

Image Analyst
Image Analyst 2019-5-12
If you have the Image Processing Toolbox, you can simply use ismember() followed by regionprops() and in 2 lines of code be done. Try this:
% Define input data:
n=[1 2 7 9];
PA = [1 3 10 1 2 8 6 2 7 11 7 9 5 9];
PB = [1 10 1 2 11 6 2 7 3 7 9 5 8 9];
% Find out where n occurs in PA:
[ia, ib] = ismember(PA, n)
% Extract the values for the regions into a structure array.
props = regionprops(~ib, PA, 'PixelValues');
% Basically we're already done, but if you want the values
% in a cell array instead of a structure array, do this:
for k = 1 : length(props)
CA{k} = props(k).PixelValues;
end
% Display what we got in the command window.
celldisp(CA)
You get exactly what you asked for. Repeat for CB. Personally I prefer structure arrays over cell arrays but you can use whichever you want.
  3 个评论
Image Analyst
Image Analyst 2019-5-12
You simply use the index like a regular index, and the field are whatever names they are or you want to call them. For example, if you also had measurements of the indexes in the region, the average value in the regions, and the length of the regions you could simply use the same index and the proper field names, like props(k).PixelIdxList, props(k).MeanIntensity, props(k).Area. props just comes out with whatever fields you asked for when you called regionprops() so they're there automatically. You can also have the measurements returned in a table, which is also more convenient than a cell array if you have multiple regions in your data.
Hang Vu
Hang Vu 2019-5-13
Image Analyst, Thank you so much for your time! It's really cool.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by