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

19 次查看(过去 30 天)
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
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

Awais Saeed
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 个评论
Catherine Law
Catherine Law 2022-2-25
thanks so much for your help, but this gives me a vector for s whose length is less than T, and I need them the same size for plotting etc later in my code, any idea why this might be happening? I tried making it
s(i+1) = stimuli(1,idx);
as I thought this would also shift them across 1 to account for T=0 being in column 1, but that didn't solve the length issue?

请先登录,再进行评论。

类别

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

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by