How do I extract elements of an array having their indexes in another array?

I have two arrays: one with data points ( b, averaged every n points from a longer array a) and another one with specific indexes ( idx) that I got from a previous classification function of these data points ( P).
Please check my code:
n = 24459; % average every n values
a = data.streams.EMGP.data; % original array
b = arrayfun(@(i) mean(a(i:i+n-1)),1:n:length(a)-n+1)'; % the averaged vector
filename= 'stim_rat36_20180209_3_predictions';
[~,~,PP]=xlsread(filename,'C1:C5451');
P = str2double(PP); %classification for each data point
idx=0; %get the index of all values classified in category 1.
for i = 1: length(P)
if P(i)==1
idx = [idx,i];
end
end
EMGP=zeros(size(idx));
for j = 1: length(idx)
EMGP=b(idx(j));
end
In array idx, I have the positions of all datapoints of b that are classified in category 1. I want to creat a new array, EMGP, with all these specific values from b with indexes stated in idx. Then, I want the average value of EMGP.
How can I do this? Something is wrong if my loop while creating EMGP.
Please help. Thank you all!

 採用された回答

dpb
dpb 2018 年 2 月 20 日
編集済み: dpb 2018 年 2 月 20 日
Instead of looping, just use Matlab logical indexing...your solution should look like
idx=[]; %get the index of all values classified in category 1.
for i = 1: length(P)
if P(i)==1, idx = [idx,i]; end
end
because your way has a zero element which is invalid array index.
"The Matlab way" is simply
EMGP=b(P==1);
though. See <matrix-indexing>

3 件のコメント

Would it be
EMGP = b(P==1)
?
Carlos Goncalves Moreira
Carlos Goncalves Moreira 2018 年 2 月 20 日
Yes! Wow, so simple.. Thanks!!
dpb
dpb 2018 年 2 月 20 日
Good catch, BNb...I dup'ed b instead of using P for the test array...

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2018 年 2 月 20 日

編集済み:

dpb
2018 年 2 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by