how do I find the locations of values in a matrix?
2 views (last 30 days)
Show older comments
I want to make a matrix with the location of values in an array. This is what i'm trying to do. The first column of TT is in matlab serial date time.
j = 1;
tol = 0.001;
for i = datenum(2018,1,1,00,00,00):0.020833:datenum(2018,12,4,00,00,00)
[ii,jj]= find(abs(TT(:,1)-i)< tol);
I(j,:) = size(ii);
switch I(j,1)
case 0
MAT(j,:) = nan(1,length(TT(1,:)));
otherwise
MAT(j,:) = TT(I(j,1),:);
end
j = j+1;
end
As it is, I'm pretty sure I is just giving me the number of data points with that value but i'd like to have I be the location of the value in TT. For example, if the first value of i is in the 45th row of TT, I'd like I(1,1) to be 45. Is there a way to do that? Thanks in advance!
0 Comments
Accepted Answer
Stephen23
on 25 Nov 2018
Edited: Stephen23
on 25 Nov 2018
DN = datenum(2018,1,1,00,00,00):0.020833:datenum(2018,12,4,00,00,00);
[ida,idb] ismembertol(DN,TT(:,1),0.001)
You will probably find this of interest:
idb(ida)
4 Comments
Stephen23
on 25 Nov 2018
Edited: Stephen23
on 25 Nov 2018
"yeah but did you read what I'm trying to do? Your suggestion gives me pretty much the same thing I already had."
This seems to be your main query:
"For example, if the first value of i is in the 45th row of TT, I'd like I(1,1) to be 45. Is there a way to do that?"
When I look at your code you seem to be attempting to construct a matrix MAT whose rows are taken from TT, and which correspond to the datenumbers that you defined. So that is what I tried to help you with, by showing you a simpler way of doing this than using a loop. Here is a complete working example:
>> DN = [737061;737063;737069]; % i.e. your datenum():30/60/24:datenum() vector.
>> TT = [737060,0;737061,111;737062,222;737063,333] % the input matrix.
TT =
737060 0
737061 111
737062 222
737063 333
>> [ida,idb] = ismembertol(DN,TT(:,1)); % Find DN values in first colum of TT.
>> mat = nan(numel(DN),size(TT,2)); % preallocate output matrix.
>> mat(ida,:) = TT(idb(ida),:) % put matched rows of TT into output matrix.
mat =
737061 111
737063 333
NaN NaN
This is also the advice that you were given in an answer to your earlier question:
Of course, if that is not what you are trying to achieve, then please explain what inputs you have and what outputs you need to get, and how the outputs should be derived from the inputs. It is most useful for us when you explain what you are trying to do, i.e. what your task/goal is.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!