substitution of values if is verified a condition
2 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a series of touristic trajectories in userTouristicTraj.touristicData.touristicTraj2 (attached); I want compare every pairs of coordinates in the array with the values in the first two columns of Clusters (attached): if there is a corrispondence, I want create a new array that instead the coordinates have the corresponding value in the 4 column of Clusters.
Example
userTouristicTraj(1).touristicData(1).touristicTraj2
ans =
38.1153 13.3781
38.1190 13.3742
I search this pairs
(38.1153 13.3781) (38.1190 13.3742)
in Clusters(:,1:2); if I find (38.1153 13.3781), put in userTouristicTraj(1).touristicData(1).traj the corrispondent value in Clusters(:,4) so
userTouristicTraj(1).touristicData(1).traj = (1; 1)
I want to do this for all the values in userTouristicTraj.touristicData.touristicTraj2. Can you help me? I hope the question is clear
0 个评论
采纳的回答
Guillaume
2017-5-31
编辑:Guillaume
2017-5-31
This should work:
for userTouristicTrajidx = 1:numel(userTouristicTraj)
for touristicDataidx = 1:numel(userTouristicTraj(userTouristicTrajidx).touristicData)
touristicTraj = userTouristicTraj(userTouristicTrajidx).touristicData(touristicDataidx).touristicTraj2;
traj = nan(size(touristicTraj, 1), 1);
if ~isempty(touristicTraj)
[found, whichrow] = ismember(touristicTraj, Clusters(:, [1, 2]), 'rows');
traj(found) = Clusters(whichrow(found), 4);
end
userTouristicTraj(userTouristicTrajidx).touristicData(touristicDataidx).traj = traj;
end
end
Note: This is using ismember which means that the numbers must be exactly identical*. If the numbers in touristicTraj2 and Clusters were obtained from different calculations, then it is very likely they won't be exactly the same (e.g. 0.1+0.1+0.1 is not the same as 0.3). If that is the case, then use ismembertol instead. ismembertol is significantly slower than ismember.
Note 2: I don't know how you generated your touristicTraj2 fields but some of them are empty with size (0, 0). It would have been much better to create them empty with size (0, 2). While for most purpose both are the same (just empty arrays), it matters for ismember. Using the latter empty would have avoided the if ~isempty(touristicTraj) test.
Note 3: You haven't specified what to write when no match is found. I've put NaN. Replace as appropriate.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!