How can I get the number between 2 numbers?

4 vues (au cours des 30 derniers jours)
Hang Vu
Hang Vu le 12 Mai 2019
Commenté : Hang Vu le 13 Mai 2019
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]};

Réponse acceptée

dpb
dpb le 12 Mai 2019
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 commentaire
Hang Vu
Hang Vu le 13 Mai 2019
Modifié(e) : Hang Vu le 13 Mai 2019
Thank you so much for the help!

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 12 Mai 2019
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 commentaires
Image Analyst
Image Analyst le 12 Mai 2019
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 le 13 Mai 2019
Image Analyst, Thank you so much for your time! It's really cool.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by