i need to make a matrix count a given set of repeated elements but it doesnt work at all

1 次查看(过去 30 天)
The variable mtx_pstn are the positions (i,j) of each element of a 4x6 matrix, and mtx_cord is a variable that stores a set of coordinates (or points if you wanna see it that way). I wanna count how many times there is a point with the same coordinates as the element position stored in mtx_pstn, that's why i use Lia_reps to make the scan, and after that i create pts_dsty_mod to count the repeated elements; but after counting, if there's more than one repetition of an element, it will just store a 1 instead of a 2 or 3, etc. so that's where im having trouble.
Also, the points stored in mtx_cord are randomly generated each time you run the script. I'd appreciate if you could help me out with this!
Lia_reps=ismember(mtx_pstn, mtx_cord, 'rows'); %Makes a scan of the points that are inside an interval of the matrix position
pts_dsty_mod=ones(size(grid_size)-1);
for i=(1:length(Lia_reps))
if Lia_reps(i) == 1
pts_dsty_mod(i)=pts_dsty_mod(i)+1;
else
pts_dsty_mod(i)=pts_dsty_mod(i);
end
end
pts_dsty_mod=pts_dsty_mod-1
pts_dsty_mod =
0 0 0 1 1 1
0 0 0 1 0 1
0 0 1 0 0 1
0 0 0 0 0 1
  2 个评论
Jan
Jan 2019-6-26
编辑:Jan 2019-6-26
What is the purpose of this line:
pts_dsty_mod(i)=pts_dsty_mod(i);
? The names of the variables are such cryptic, that it impedes understanding, what you are asking for. Remember, that these arrays are all numbers in Matlab. So if you create this as a subfunction, it is sufficient to use e.g. "Lia" instead of "Lia_reps".
Itr would be easier to answer, if you provide some test data and explain, what you want as output. "but after counting, if there's more than one repetition of an element, it will just store a 1 instead of a 2 or 3, etc" - This is hard to understand.
Guillaume
Guillaume 2019-6-26
Also,
if Lia_reps(i) == 1
is clearer, simpler, faster and more logical as:
if Lia_reps(i)
Lia_reps(i) is already true or false, so if Lia_reps(i) is already if true or if false. What you have written converts the true or false value in a double 0 or 1, compare that 0 or 1 to 1 which will result in the same true or false value as you started with. You've just wasted time recreating your original value.

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2019-6-26
Maybe all you need is:
[Lia, LocB] = ismember(points, coor, 'rows');
n = histcounts(LocB, 1:size(B, 1))

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by