필터 지우기
필터 지우기

Creating index and replacing values

조회 수: 8 (최근 30일)
Inna Pelloso
Inna Pelloso 2021년 6월 21일
댓글: Inna Pelloso 2021년 6월 21일
Hi,
I have A = [0 0 1 0 1 0 0], and B = [ "030121", "030221", "030321"]
I want to create C = [ "030121", "030121", "030221", "030221", "030321", "030321", "030321"], by looking at A, and treating each sucessive sequence beginning with 1 as a new day, and replacing with the corresponding date from B. his is a generalization of a large problem.
Any help would be appreciated!
Inna
  댓글 수: 2
Scott MacKenzie
Scott MacKenzie 2021년 6월 21일
Note that
B = [ '030121', '030221', '030321']
is the same as
B = '030121030221030321'
and that
C = [ '030121', '030121', '030221', '030221', '030321', '030321', '030321']
is the same as
C = '030121030121030221030221030321030321030321'
Did you perhaps intend these to be strings, for example
B = ["030121", "030221", "030321"]
Inna Pelloso
Inna Pelloso 2021년 6월 21일
Correction made. I intended them to be strings.

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2021년 6월 21일
A = [0 0 1 0 1 0 0];
B = [ "030121", "030221", "030321"];
I'm going to assume that A does not start with 1, or if it does that indicates the first element of the result should be the second element in B.
C = 1 + cumsum(A)
C = 1×7
1 1 2 2 3 3 3
D = B(C)
D = 1×7 string array
"030121" "030121" "030221" "030221" "030321" "030321" "030321"
Alternately if you're doing this to build a datetime array:
D2 = datetime(2021, 3, C)
D2 = 1×7 datetime array
01-Mar-2021 01-Mar-2021 02-Mar-2021 02-Mar-2021 03-Mar-2021 03-Mar-2021 03-Mar-2021
D2.Format = 'MMddyy'
D2 = 1×7 datetime array
030121 030121 030221 030221 030321 030321 030321
  댓글 수: 2
Inna Pelloso
Inna Pelloso 2021년 6월 21일
Elegant solution!
Scott MacKenzie
Scott MacKenzie 2021년 6월 21일
@Steven Lord Hmm, cumsum. Yes, that's way to do this. Thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Scott MacKenzie
Scott MacKenzie 2021년 6월 21일
Below is a loop solution. There might be a way to vectorize this -- not sure.
A = [0 0 1 0 1 0 0];
B = [ "030121", "030221", "030321"];
M = [];
k = 1;
for i=1:length(A)
if A(i) == 1 % new day
k = k + 1;
end
M = [M B(k)];
end
Output:
M =
1×7 string array
"030121" "030121" "030221" "030221" "030321" "030321" "030321"
Obviously, the number of 1s in A can't exceed the number of strings in B (minus 1).
  댓글 수: 1
Inna Pelloso
Inna Pelloso 2021년 6월 21일
appreciate the help! Cumsum is rather elegant!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by