[英]“Find” function with two outputs needed?
I am trying to use a 'for' loop find the number of values in a randomly generated vector that are 1) greater than 0.5 and output also 2) the number of values greater than 0.8. 我正在尝试使用“ for”循环在随机生成的向量中查找1)大于0.5的值的数量,并输出2)大于0.8的值的数量。 This is what I have 这就是我所拥有的
function bigger1 = bigger(input, max)
for max = 0.5:0.3:0.8;
index = find(input > max);
end
bigger1=length(index);
end
For instance, with the input bigger([.1 .2 .3 .4 .5 .6 .7 .8 .9 3 5]) I would like to output "6" and "3" 例如,使用更大的输入[[.1 .2 .3 .4 .5 .6 .7 .8 .9 3 5])我想输出“ 6”和“ 3”
So far it only gives me the output for one of the 'max' values. 到目前为止,它只为我提供了“最大”值之一的输出。
There's a couple of things not quite right with what you're doing. 您所做的事情有些不对劲。
max
as a variable name. 不要使用max
作为变量名。 It is also the name of a built-in function, and using it as a variable name shadows that function. 它也是内置函数的名称,并将其用作变量名可屏蔽该函数。 BAD practice. 坏习惯。 input
input
相同 max
as an input, while you re-define it as the loop variable. 您将max
作为输入,同时将其重新定义为循环变量。 This new definition overwrites the old one, so the max
function input is useless. 此新定义将覆盖旧的定义,因此max
函数输入无用。 index
is--the output of the next call to find
. 在每次迭代时,您都重新定义什么index
-下一个find
调用的输出。 Therefore, don't be surprised that you have only the outcomes of the last iteration. 因此,只有最后一次迭代的结果就不会感到惊讶。 find
will actually find the indices to all true values, in general. 通常,您的find
实际上会找到所有真实值的索引。 You have to sum all these occurrences, not find the index. 你必须要总结所有这些事件,没有找到索引。 A better implementation: 更好的实现:
function out = bigger(in, mx)
out = zeros(size(mx));
for ii = 1:numel(mx)
out(ii) = sum(in > mx(ii)); end
end
A more "hacky" one eliminates one line of code, while preserving performance: 更加“ hacky”的代码消除了一行代码,同时保留了性能:
function out = bigger(in, mx)
for ii = numel(mx):-1:1
out(ii) = sum(in > mx(ii)); end
end
The one that will probably teach you the most once you've figured it all out (it's also fastest BTW): 一旦您弄清楚了所有可能会教给您最多的知识(它也是最快的BTW):
out = @(in, mx) reshape( sum(bsxfun(@gt, in(:).', mx(:)), 2), size(mx) );
Since you're using only one variable in the for loop, you overwrite it in each iteration - so it is natural that you get only one value. 由于在for循环中仅使用一个变量,因此在每次迭代中都将其覆盖-因此很自然地只有一个值。 Ie, if you want to store both, make a vector 2 by 1. 即,如果要同时存储两个向量,则将向量乘以1。
Adiel has explained how to do it your way in a comment, however this is not really the Matlab way to solve this problem. Adiel在评论中已经解释了如何使用此方法,但是,这实际上并不是Matlab解决此问题的方法。 Here is a neater way to do it: 这是一种更整洁的方法:
I = rand(50,1); %// btw input is a bad choice of variable name as it is a built-in matlab function which you are overriding.
bigger(1) = sum(I > 0.5);
bigger(2) = sum(I > 0.8);
or to put this in a loop: 或将其循环:
limits = [0.5, 0.8];
for n = 1:length(limits)
bigger(n) = sum(I > limits(n));
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.