How to replace values?

How can I replace values? I've a matrix of 3653x337 Let's consider I've
  • dates values
  • 0101 0
  • 0102 0
  • 0103 0
  • 0104 1
  • 0105 0
  • 0106 0
  • 0107 0 ....
I need a function to find all these "1"'s in my matrix and to replace it for two days before and after I've a "1".
Thanks!

4 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 7 月 16 日
This is not clear
Ugur
Ugur 2013 年 7 月 16 日
sorry! I wish to copy in the 2 days before and after the "1" that I have. For example here we have 1 only for 4th January (0104) I want now Matlab to copy 1 to 0102,0103 and 0105, 0106.
Cedric
Cedric 2013 年 7 月 16 日
And why not to 0101 and 0107?
the cyclist
the cyclist 2013 年 7 月 16 日
I think he means that if there is a 1 in the second column, put two more 1's before and two more after (all in the second column).

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

 採用された回答

the cyclist
the cyclist 2013 年 7 月 16 日

0 投票

Here is a simple way that should be easy to understand. I am sure there are slicker ways, but maybe this will suit your purpose.
oldIndex = find(values==1);
newIndex = unique([oldIndex-2; oldIndex-1; oldIndex; oldIndex+1; oldIndex+2]);
values(newIndex) = 1;

3 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 7 月 17 日
newIndex = unique([oldIndex-2; oldIndex-1;oldIndex+1; oldIndex+2]);
without oldIndex
Ugur
Ugur 2013 年 7 月 17 日
it works very well!!!
Thanks!
Jos (10584)
Jos (10584) 2013 年 7 月 17 日
This errors when values has 1's in the beginning or the end ... Moreover, you can skip unique.

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2013 年 7 月 17 日

0 投票

Here's a one-liner:
values = [0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1]
values(max(min(bsxfun(@plus,reshape(find(values==1),[],1),-2:2),numel(values)),1))=1
or in more readable format:
values = [0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1]
oldIndex = find(values==1)
newIndex = bsxfun(@plus, oldIndex(:), -2:2)
newIndex = max(newIndex,1)
newIndex = min(newIndex,numel(values))
values2 = values % work on a copy
values2(newIndex) = 1
Note that you do not need unique numbers for right-hand indexing
B = [0 0 0]
B([2 2 2 2 2 2]) = 1

3 件のコメント

Ugur
Ugur 2013 年 7 月 17 日
I've an error message saying that "undefined function 'nume1' for input arguments of type 'double'".
Jos (10584)
Jos (10584) 2013 年 7 月 17 日
you should type numel with an lower case L instead of the digit 1 ...
Ugur
Ugur 2013 年 7 月 20 日
: )
thank you a lot!!!

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

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by