What is the inverse of find() function in matlab

寵の児 提交于 2020-05-23 13:15:49

问题


In Matlab I can find all non zero entries in a vector like this:

>> v = [0 1 0 0 1]

v =

     0     1     0     0     1

>> indices = find(v)

indices =

     2     5

Assuming that my vector v can only have 0 and 1 values, what is a simple way to reproduce v from the indices vector?


回答1:


you have to know what the shape v is (i.e. how long v is if it's a vector as in your example), but once you know that it's trivial:

n = 5;
v_reconstructed = zeros(1, n);
v_reconstructed(indices) = 1;

if you don't know how long v is then you won't capture any 0s after the last 1 in v...

BTW if you are working with sparse matrices then you might want this actually:

v = sparse([0 1 0 0 1]);
v_reconstructed = full(v);



回答2:


i used to use sparse and full but now i switched to accumarray, because it has simpler format.

in your example:

   v=accumarray([2;5],1)'

additionally, you can also cycle values (i think), according to the first matlab example:

Create a 5-by-1 vector, summing values for repeated 1-D subscripts:
   subs = [1; 2; 4; 2; 4];
   A = accumarray(subs, 101:105)

of course, according to its name, this function is built to do fancier things.



来源:https://stackoverflow.com/questions/25931454/what-is-the-inverse-of-find-function-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!