Compare and modify random vector with evenly spaced vector
显示 更早的评论
A is vector randomly generated and length varies from 5-7. B is vector of evenly spaced values of length 10. Every element of A is to be checked with every class (bin) of element of B.
A=[0.1, 0.21, 0.346, 0.59, 0.744, 1]; % actually created with random numbers
B=linspace(min(A),max(A),10); % linear 10 pieces
Value 0.1 of A is present in B (say, class 0.1-0.2), hence, it is kept in A. If any value in A does not belong to the class in B, then it is asigned as zeros. Finally, the length of A would enhance to that of B. The expected result would be as like:
A=[0.1,0.21,0.346,0,0.59,0,0.744,0,1];
2 个评论
John D'Errico
2019-9-1
编辑:John D'Errico
2019-9-1
A BAD way to code:
B=min(A):1/9:max(A); % linear 10 pieces
A better way to code, for the same target result:
B=linspace(min(A),max(A),10); % linear 10 pieces
Learn to use the tools in MATLAB properly, here, linspace is a terribly valuable tool.
Why is linspace better? Because if you explicitly want 10 values that are linear over that interval, linspace gives you them, and does so accurately. You only need to indicate the NUMBER of elements, thus an integer value.
What happens when you use colon, and you specify the increment? Here, you need to be careful, to compute the correct spacing yourself.
A=[0.1, 0.21, 0.346, 0.59, 0.744, 1]
A =
0.1 0.21 0.346 0.59 0.744 1
B=min(A):1/9:max(A)
B =
0.1 0.21111 0.32222 0.43333 0.54444 0.65556 0.76667 0.87778 0.98889
length(B)
ans =
9
B(end)
ans =
0.988888888888889
B=linspace(min(A),max(A),10)
B =
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
length(B)
ans =
10
Do you see what happened? The increment that you used was not in fact correct. The last element of B when you created it using colon was
B=min(A):1/9:max(A);
B(end)
ans =
0.988888888888889
It was not 1, because 1/9 is not the correct increment to achieve that result. You made an error of thought, using the wrong increment.
Again, learn to use linspace, because that makes your code better. It prevents you from making simple mistakes.
Mukund
2019-9-1
采纳的回答
更多回答(1 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!