实现matlab查找功能 [英] Implementing the matlab find function

查看:1328
本文介绍了实现matlab查找功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在MATLAB中找到矩阵中所有非零元素的坐标。我知道 find 使得这非常简单。问题是我需要定义矩阵的长度,然后才能填充它。我相信这是不可能的使用 find ,因为它会创建自己的向量。所以我必须找到另一个办法。如果我正在寻找1个元素,那么也很容易。让我用一个例子。假设我有一个矩阵 M 500×500,其中 60 我想找到坐标。所以我可以从以下开始:

$ pre $ code $ for $ i $ 1 $ 500
$ j $ 1 $ 500 b $ b如果M(i,j)== 1
row = i;
col = j;
end
end
end

但是我想多一个点,我需要在填充之前定义一个向量的长度。所以我会做赌注,有少于100的矩阵:

  v =零(1,100)
w = zeros(1,100)

我如何填写这个向量如下。假设我已经填充了vector的 N 元素,所以下一个元素将是:

pre>如果M(i,j)== 1&& amp;& amp; amp; amp; amp;< i〜= v(1)&& i〜= v(2)&& ...&& i〜= v(N)&& j〜= v(1)&& ...&& i = v(N)
v(N + 1)= i
w(N + 1)= j
end
end
end
所以我需要另一个for循环包含所有这些,它将遍历向量的元素 v
$ b> / code>和 w ,我需要一些循环来确保if语句正在被使用。



有没有人有任何想法如何做到这一点?



亲切的问候,



杰西

解决方案

这是另一种方式,浪费:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ));
inds = M〜= 0;
ii = ii(inds);
jj = jj(inds);


I am trying to find the coordinates of all non zero elements in a matrix, in MATLAB. I know that find makes this very easy. The problem is that I need to define the length of my matrix before I can fill it up. I believe this is impossible using find, since it will make its own vector.

So I have to find another way. If I'm looking for 1 element it will be easy as well. Let me use an example. Say I have a matrix M of 500×500, with 60 ones somewhere. I want to find the coordinates. So I can start with:

for i = 1:500
  for j = 1:500
    if M(i,j) == 1
       row = i;
       col = j;
    end
  end
end

But I want more then one point, and I need to define the length of a vector before filling it. So I'll make the gamble that there are less then 100 ones in the matrix:

v = zeros(1,100)
w = zeros(1,100)

And how I essentially want to fill this vector is as follows. Let's say I have already filled N elements of the vector, so the next one will be:

for i = 1:500
  for j = 1:500
    if M(i,j) == 1 && i ~= v(1) && i ~= v(2) && ... && i ~= v(N) && j ~= v(1) && ... && i ~= v(N)
     v(N+1) = i
     w(N+1) = j
    end
  end
end

So I need another for loop containing all this, which will run through the elements of the vectors v and w, and I need some loop that will make sure the right if statement is being used.

Does anyone have any idea of how to do this?

Kind regards,

Jesse

解决方案

Here's another way, nice & wasteful:

[jj,ii] = meshgrid(1:size(M,2),1:size(M,1));        
inds = M~=0;
ii   = ii(inds);
jj   = jj(inds);

这篇关于实现matlab查找功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆