# If value in one vector is in another, assign the value of the other column of the second vector to a third

10 ビュー (過去 30 日間)
Catherine Law 2022 年 2 月 24 日
コメント済み: Catherine Law 2022 年 2 月 25 日
I have 3 vectors (these are simplified versions I created as the real data points are vast and I don't know how to put them in here and I need the concept of the task, but this means I can't solve this by assigning specific values I need a general if statement).
T = 0:20;
s = zeros(1,lenth(T));
stimuli = [4 8 14 2 16 6 15 12 3 ; 6 8 15 12 3 11 19 16 2];
I want to see if values of T are in row 2 of stimuli, and if they are I want to assign the corresponding value in row 1 of stimuli to the column in s equal to time T.
Eg, if T=19, which is in row 2 of stimuli, I want 15 to become the value in column 20 of s (20 not 19 as I'm including the 0 as the first value)
Here is my current code:
for i = 1:length(T)
if ismember([T(i)],stimuli(2,:)) %if there is a stimulus at time
s(i) = stimuli(1,(stimuli(2,T(i)))); %assigne the stimulus value at that time to s
end
end
does anyone know how I can do this? I can provide more info on my project if needed, but hopefully this will be enough :)

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

### 回答 (2 件)

Jan 2022 年 2 月 24 日
I do not understand exactly, what you are asking for. A guess:
T = 0:20;
s = zeros(1, numel(T));
stimuli = [4 8 14 2 16 6 15 12 3 ; 6 8 15 12 3 11 19 16 2];
[match, index] = ismember(T, stimuli(2, :));
s(match) = stimuli(1, index(match))
s = 1×21
0 0 3 16 0 0 4 0 8 0 0 6 2 0 0 14 12 0 0 15 0
##### 0 件のコメント表示非表示 -1 件の古いコメント

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

Awais Saeed 2022 年 2 月 24 日
T = 0:20;
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
s = zeros(1,length(T));
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
stimuli = [4 8 14 2 16 6 15 12 3 ; 6 8 15 12 3 11 19 16 2]
stimuli = 2×9
4 8 14 2 16 6 15 12 3 6 8 15 12 3 11 19 16 2
for ii = 1:1:numel(T)
% find if T(ii) is in row 2 of stimuli
idx = find(T(ii) == stimuli(2,:));
if(isempty(idx) == 0)
% if yes, pick corresponding column value from row1 in stimuli
% and put it in s
s(ii) = stimuli(1,idx);
end
end
disp(int2str(s))
0 0 3 16 0 0 4 0 8 0 0 6 2 0 0 14 12 0 0 15 0
##### 4 件のコメント表示非表示 3 件の古いコメント
Catherine Law 2022 年 2 月 25 日
actually nevermind it was an issue elsewhere in my code thanks so so much!!

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

### カテゴリ

Find more on Matrix Indexing in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by