Reputation: 52850
My code works with this kind of structures
K>> mlf=sparse([],[],[],2^31+1,1); mlf(1)=1; mlf
mlf =
(1,1) 1
but it fails with this kind of inputs below where I choose the terms in mlf that are larger than zero (I cannot understand how this selection makes the input different)
K>> mlf=sparse([],[],[],2^31+1,1); mlf(1)=1; mlf(mlf>0)
ans =
(1,1) 1
where the only visual difference is some tabs/spaces.
Please, explain how they are different.
Upvotes: 0
Views: 83
Reputation: 52850
Rody Oldenhuis recommended the whos
>> mlf=sparse([],[],[],2^31+1,1); mlf(1)=1; mlf=mlf(mlf>0)
mlf =
(1,1) 1
>> whos mlf
Name Size Bytes Class Attributes
mlf 1x1 32 double sparse
>> mlf=sparse([],[],[],2^31+1,1); mlf(1)=1; mlf
mlf =
(1,1) 1
>> whos mlf
Name Size Bytes Class Attributes
mlf 2147483649x1 32 double sparse
which shows the key problem: the size of the structures have changed. chappjc provided a way to solve this problem by introducing new variables.
Upvotes: 0
Reputation: 30589
I think the answer is the size of the resulting array, as Rody suggested:
>> mlf=sparse([],[],[],2^31+1,1); mlf(1)=1; size(mlf(mlf>0))
ans =
1 1
>> mlf=sparse([],[],[],2^31+1,1); mlf(1)=1; size(mlf)
ans =
2147483649 1
*EDIT 1: Indexing works properly:
>> mlf(mlf>0) = 2
mlf =
(1,1) 2
This is functionally equivalent to using find
:
>> mlf(find(mlf)) = 2
mlf =
(1,1) 2
It seems like a good conclusion that display
is formatting the output with enough space for an element at (2147483649,1)
, but only when you are indexing for an assignment to that element (think lvalue vs rvalue).
*EDIT 2: If you are going after those elements in a full (not sparse) variable, use full
:
>> full(mlf(mlf>0))
ans =
1
*EDIT 3: To assign to the last element according to the dimensions of mlf
rather than to the last non-zero element,
>> mlf(numel(mlf))=77
mlf =
(1,1) 1
(2147483649,1) 77
*EDIT 4: To remove negative values:
mlf(mlf<0)=0; % or mlf(find(mlf<0)) = 0;
If you want to make a copy and remove the negatives:
mlf2 = mlf;
mlf2(mlf2<0) = 0;
mlf3 = mlf;
mlf3(mlf3>0) = 0;
Then you have mlf
with all values, mlf2
with only positives, and mlf3
with only negatives. The key thing with this is that the size stays the same as with the original mlf
so you are able to use the things such as end
in the original way based on the size of the sparse, hurray!
Upvotes: 2