How to modify the following code
1 次查看(过去 30 天)
显示 更早的评论
good , using the following code I want to create all the substrings of a sequence s . Eg
s = [ 1 1 1 0 0 1 0 1 ]
using the following code , where n = length substrings :
if true
% code
N = length ( s ) ; % number rows
n = 4 ;
A = Hankel(1: N -n +1 , N- n +1: N);
k = 0: n-1;
idx = [ ] ;
for ii = 1 : size ( A, 1 )
p = A ( ii , :) ;
while p (end , end) + k ( end) < = N
p = [p , p ( end , :) + k] ;
end
idx = [ idx , p ] ;
end
[ j1 , j2 , j2 ] = unique ( s ( idx ) , ' rows ');
end
The code returns me an array with the result of combinations in this sequence:
0 0 1 0
0 1 0 1
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0
My question is this : How I can change the code so that instead of a single sequence s me , I make the rows of a matrix. For example , I want to calculate the substrings of length 4,5 ... n of the rows of the following matrix :
1 1 1 0 0 1 0 1
0 1 1 0 0 0 0 0
and that all combinations the same length of both rows store in a single array , using the above code . How do? thank you very much
4 个评论
Roger Stafford
2013-11-15
I should point out that the line with
unique(s(idx),'rows');
will not work as it stands. You would need to write
unique(reshape(s(idx),n,[])','rows')
to get the results you claim.
Also if the length(s) is sufficiently large that the while-loop executes twice in succession, then the line
p = [p,p(end,:)+k];
will fail. It should be replaced by
p = [p,p(end,end-n+1:end)+k];
采纳的回答
Roger Stafford
2013-11-15
To use more than one row in s, in place of N = length(s) you can do this:
[M,N] = size(s);
Then use your code (hopefully corrected in the while-loop as I recommended earlier) to create the row vector idx. Then do this:
m = length(idx);
idx = repmat(idx,1,M)+reshape(repmat(0:N:(M-1)*N,m,1),1,[]);
s = s';
j1 = unique(reshape(s(idx),n,[])','rows');
4 个评论
Roger Stafford
2013-11-16
You made one change in your original code and that is apparently what is causing you the trouble. In your original code you had:
idx = [idx,p];
just after you exit the while-loop and just before the end of the for-loop. However, in the more recent version which failed with the error message "Error using vertcat CAT arguments dimensions are not consistent", you had written instead:
idx = [idx;p];
with a semicolon instead of a comma. That would invalidate the coding which I suggested to you. My assumption was that idx would emerge from the for-loop as a vector with only a single row, as you had it originally. I recommend you replace the semicolon with a comma and try it out again.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!