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

20 vues (au cours des 30 derniers jours)
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 :)

Réponses (2)

Jan
Jan le 24 Fév 2022
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 le 24 Fév 2022
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 commentaires
Catherine Law
Catherine Law le 25 Fév 2022
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?
Catherine Law
Catherine Law le 25 Fév 2022
actually nevermind it was an issue elsewhere in my code thanks so so much!!

Connectez-vous pour commenter.

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by