Matlab find index of matched elements and replace values
65 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Benvaulter
el 15 de En. de 2016
Comentada: Aria Ghazavi
el 3 de Dic. de 2019
I want to create an array of indices using Matlab's find-function. Here is what I need to do:
I have an array a1 containing time data in the datenum format (incomplete set) and an array v1 (same length as a1) containing some values.
I now created a new array a2 also containing time data in the datenum format (this time complete set, hence length(a2) > length(a1)) and initialized an array v2 with zeros with length(a2).
What I want to do is to replace the zeros in v2 with the data in v1 where a1 matches a2.
I think this is a case for indexing, where I ultimately want to do the following:
v2(ind) = v1; % whereas ind contains the indices of the matched elements of a1 and a2
However when I try to create an array ind to store the indices where a1 matches a2 I get an error related to the dimensions:
ind = find(a1==a2);
Error: Matrix dimensions must agree
Starting point:
a1 = [2;3;4;6;9]; % simplified time-vector ("incomplete")
v1 = [1;2;1;1;2]; % data for each time-point in a1
a2 = [1;2;3;4;5;6;7;8;9;10]; % "complete" time-vector
v2 = zeros(length(a2),1); % initialize final output variable
Desired Outcome:
v2 = [0;1;2;1;0;6;0;0;2;0] % values of v1 inserted where a1 matches a2
Can someone help me out here?
Many thanks in advance!
0 comentarios
Respuesta aceptada
jgg
el 15 de En. de 2016
Editada: jgg
el 15 de En. de 2016
I would do it this way:
ta = [735965;735966;735968;735969;735971]
data = [1;2;4;5;7];
act_time = [735965:735971];
act_data = [0;data];
[~,ind] = ismember(act_time,ta);
act_data = act_data(ind + 1);
However, I'd bet someone else here has a clever way that doesn't use the ismember function. I'm excited to see what other people have to say.
My basic idea is that you glom onto the start of your data a "missing" number; it could be 0 or it could be NaN, whatever you need. Then, you find the time index locations of the actual times you have in the master list of all times. The missing dates will return an index of zero, since they're missing. This corresponds to location 1 of the augmented data matrix, so you can match them up by adding 1 to the index.
3 comentarios
jgg
el 15 de En. de 2016
You should accept this answer so people can see both solutions if they have the same problem.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!