필터 지우기
필터 지우기

How can I get the number between 2 numbers?

조회 수: 4 (최근 30일)
Hang Vu
Hang Vu 2019년 5월 12일
댓글: Hang Vu 2019년 5월 13일
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
Hang Vu
Hang Vu 2019년 5월 13일
편집: Hang Vu 2019년 5월 13일
Thank you so much for the help!

댓글을 달려면 로그인하십시오.

추가 답변 (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