简体   繁体   English

在MATLAB中将值传递给稀疏矩阵

[英]Passing values to a sparse matrix in MATLAB

Might sound too simple to you but I need some help in regrad to do all folowings in one shot instead of defining redundant variables ie tmp_x , tmp_y : 听起来可能对您来说太简单了,但是我需要一些帮助进行重做以一次完成所有操作,而不是定义冗余变量, 例如 tmp_xtmp_y

X= sparse(numel(find(G==0)),2);
[tmp_x, temp_y] = ind2sub(size(G), find(G == 0));
X(:)=[tmp_x, tmp_y];

(More info: G is a sparse matrix) (更多信息: G是一个稀疏矩阵)

I tried: 我试过了:

X(:)=ind2sub(size(G), find(G == 0));

but that threw an error. 但这引发了错误。 How can I achieve this without defining tmp_x , tmp_y ? 如何在不定义tmp_xtmp_y的情况下实现此目标

A couple of comments with your code: 您的代码有几点注释:

  1. numel(find(G == 0)) is probably one of the worst ways to determine how many entries that are zero in your matrix. numel(find(G == 0))可能是确定矩阵中有多少个零条目的最差方法之一。 I would personally do numel(G) - nnz(G) . 我个人会做numel(G) - nnz(G) numel(G) determines how many elements are in G and nnz(G) determines how many non-zero values are in G . numel(G)确定的许多元素是如何在Gnnz(G)确定许多非零值如何在G Subtracting these both would give you the total number of elements that are zero. 将这两个元素相减将得出的元素总数为零。
  2. What you are doing is first declaring X to be sparse... then when you're doing the final assignment in the last line to X , it reconverts the matrix to double . 您要做的是先声明X为稀疏...然后在最后一行中将最终赋值给X ,它将矩阵重新转换为double As such, the first statement is totally redundant. 因此,第一条陈述是完全多余的。

If I understand what you are doing, you want to find the row and column locations of what is zero in G and place these into a N x 2 matrix. 如果我了解您在做什么,则想在G找到零的行和列位置,并将它们放入N x 2矩阵中。 Currently with what MATLAB has available, this cannot be done without intermediate variables. 当前使用MATLAB所提供的功能,如果没有中间变量就无法做到这一点。 The functions that you'd typically use ( find , ind2sub , etc.) require intermediate variables if you want to capture the row and column locations. 如果要捕获行和列的位置,通常需要使用的函数( findind2sub等)需要中间变量。 Using one output variable will give you the column locations only. 使用一个输出变量将只为您提供列位置。

You don't have a choice but to use intermediate variables. 您别无选择,只能使用中间变量。 However, if you want to make this more efficient, you don't even need to use ind2sub . 但是,如果要提高效率,甚至不需要使用ind2sub Just use find directly: 只需直接使用find

[I,J] = find(~G);
X = [I,J];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM