Have a matrix [0 0 0 0 0 0; 0 0 0 1 1 1; 0 0 0 0 1 1; 0 0 0 0 1 1; 0 0 0 0 0 1; 0 0 0 1 1 1]. Want Matlab, in any row it encounters 1, to replace the first three zeros before the 1 with 1 so that I will have something like this [0 0 0 0 0 0; 1 1 1 1 1 1; 0 1 1 1 1 1; 0 1 1 1 1 1; 0 0 1 1 1 1; 1 1 1 1 1 1]. How do I go about this? I have a very big matrix I am dealing with.

4 件のコメント

Williams Ackaah
Williams Ackaah 2015 年 7 月 29 日
Dear Andrei Bobrov, thanks for your brilliance. Have learnt some new functions. However, with the data I am working with, replacing the first three zeros can be at different sections of the matrix. See the example below A = [0 0 0 0 1 1 0 0 0 0 0 1 1; 0 0 0 1 1 1 0 0 0 0 1 1 1; 0 0 0 1 1 1 0 0 0 0 1 1 1; 0 0 0 0 0 1 0 0 0 0 0 0 1] and this is what I expect to generate Ans = [0 1 1 1 1 1 0 0 1 1 1 1 1; 1 1 1 1 1 1 0 1 1 1 1 1 1; 1 1 1 1 1 1 0 1 1 1 1 1 1; 0 0 1 1 1 1 0 0 0 1 1 1 1]. Thanks
Andrei Bobrov
Andrei Bobrov 2015 年 7 月 29 日
編集済み: Andrei Bobrov 2015 年 7 月 29 日
see part of my answer after 'add'
Williams Ackaah
Williams Ackaah 2015 年 7 月 31 日
編集済み: Williams Ackaah 2015 年 7 月 31 日
Dear Stephen Cobeldick, Thank you for your answer. As I mentioned, my matrix is very big (24 by 1440) and the position(s) of where the ones are first encountered is not fixed (may be different for each row). Is a for loop the way to go?
Stephen23
Stephen23 2015 年 7 月 31 日
Using loops seems reasonable to me.
Your requirements exclude the use of circshift and cumsum in a trivial combination (e.g. Andrei Bobrov's initial answer). While there might be more compact solutions, using loops is likely the least obfuscated and yet also reasonably fast.

サインインしてコメントする。

回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2015 年 7 月 29 日
編集済み: Andrei Bobrov 2015 年 7 月 29 日

1 投票

out = cumsum(circshift(A,[0,3]),2)>0;
add
m = 3
b = [zeros(size(A,1),1),diff(A,[],2)]==1;
out = cumsum(b(:,[m+1:end,1:m])-b,2)+A;
Stephen23
Stephen23 2015 年 7 月 29 日
編集済み: Stephen23 2015 年 7 月 29 日

0 投票

>> A = [0 0 0 0 1 1 0 0 0 0 0 1 1; 0 0 0 1 1 1 0 0 0 0 1 1 1; 0 0 0 1 1 1 0 0 0 0 1 1 1; 0 0 0 0 0 1 0 0 0 0 0 0 1]
A =
0 0 0 0 1 1 0 0 0 0 0 1 1
0 0 0 1 1 1 0 0 0 0 1 1 1
0 0 0 1 1 1 0 0 0 0 1 1 1
0 0 0 0 0 1 0 0 0 0 0 0 1
>> B = A;
>> for k = 1:3, B(:,4-k:end-k) = B(:,4-k:end-k) | A(:,4:end); end
>> B
B =
0 1 1 1 1 1 0 0 1 1 1 1 1
1 1 1 1 1 1 0 1 1 1 1 1 1
1 1 1 1 1 1 0 1 1 1 1 1 1
0 0 1 1 1 1 0 0 0 1 1 1 1

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 7 月 29 日

コメント済み:

2015 年 7 月 31 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by