필터 지우기
필터 지우기

merge two arrays into one

조회 수: 18 (최근 30일)
Sehoon Chang
Sehoon Chang 2021년 7월 3일
답변: Yongjian Feng 2021년 7월 3일
i am trying to merge two arrays into one array.
The goal is to create a load cycle graph of a storage system.
One array is called "charge amount" and the other array is called "discharge amount".
for example:
charge amount = [ 1 2 3 4 5 0 0 0 0 0 1 2 3 4 5 .....]
discharge amount = [ 0 0 0 0 0 -1 -2 -3 -4 -5 0 0 0 0 0 .....]
how can i merge either one of the array into the other one where the value is zero (0)?
for example:
load cycle = [1 2 3 4 5 -1 -2- 3- -4 -5 1 2 3 4 5 .....]
thank you in advance.
  댓글 수: 1
Sehoon Chang
Sehoon Chang 2021년 7월 3일
btw the elements within arrays are not in 5 element increments. the examples are just to show that there are 0 values and non-0 values

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

채택된 답변

Star Strider
Star Strider 2021년 7월 3일
One option is simply to add them:
charge_amount = [ 1 2 3 4 5 0 0 0 0 0 1 2 3 4 5];
discharge_amount = [ 0 0 0 0 0 -1 -2 -3 -4 -5 0 0 0 0 0];
load_cycle = charge_amount + discharge_amount
load_cycle = 1×15
1 2 3 4 5 -1 -2 -3 -4 -5 1 2 3 4 5
That works for this example, at least.
.
  댓글 수: 2
Sehoon Chang
Sehoon Chang 2021년 7월 3일
편집: Sehoon Chang 2021년 7월 3일
thanks! it worked :)
Star Strider
Star Strider 2021년 7월 3일
As always, my pleasure!
.

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

추가 답변 (1개)

Yongjian Feng
Yongjian Feng 2021년 7월 3일
Not sure what you really want.
  1. If those two arrays have the same length at the time, and if the ith element of one array is non-zero, the ith element of the other array is always 0 (just like those two you showed), then it is just as easy as merged = charge_amount+discharge_amount;
  2. If you need to put in extra logic then you can loop through those arrays:
charge_amount = [1 2 0 0 3 4];
discharge_amount = [0 0 5 6 0 0];
merged = zeros(1, length(charge_amount));
for i=1:length(charge_amount)
% put your logic here
% here assuming you sum them up only if one is zero, the other one is
% not
if (charge_amount(i) == 0 && discharge_amount(i) != 0) || (discharge_amount(i) == 0 && charge_amount(i) != 0)
% if one is zero and the other one is not, merge
merged(i) = charge_amount(i) + discharge_amount(i);
elseif charge_amount(i) == 0 && discharge_amout(i) == 0
% it doesn't make any difference sum them or not
else
% they are both non-zero, what do you want for this case?
end
end

카테고리

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