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 :
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)
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 ?
A couple of comments with your code:
numel(find(G == 0))
is probably one of the worst ways to determine how many entries that are zero in your matrix. I would personally do 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
. Subtracting these both would give you the total number of elements that are zero. X
to be sparse... then when you're doing the final assignment in the last line to X
, it reconverts the matrix to 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. Currently with what MATLAB has available, this cannot be done without intermediate variables. The functions that you'd typically use ( find
, ind2sub
, etc.) require intermediate variables if you want to capture the row and column locations. 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
. Just use find
directly:
[I,J] = find(~G);
X = [I,J];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.