padding an array with zeros in between elements

26 ビュー (過去 30 日間)
Gillean
Gillean 2024 年 1 月 29 日
コメント済み: Gillean 2024 年 1 月 29 日
Basically, I would like to pad an array of location peak values with zeros inbetween each, the catch is the number of zeros between each should be the difference of the two ascending elements. For example, in an array A = [7 15 21 29], with a loop I would like to pad this so it turns into,
A = [ 7 0 0 0 0 0 0 0 15 0 0 0 0 0 21 0 0 0 0 0 0 0 29 ]
I'm aware I'll have to minus 1 to the equation somewhere too. As you can see, I'm basically making an ascending integer array with the elements that were not included now included as zeros... I've been trying with for loops and if statements but to no avail unfortuantely
Thanks in advance!

採用された回答

Stephen23
Stephen23 2024 年 1 月 29 日
編集済み: Stephen23 2024 年 1 月 29 日
Assuming that A is sorted, here is a simple approach:
A = [7,15,21,29];
B = A(1):A(end);
B(~ismember(B,A)) = 0
B = 1×23
7 0 0 0 0 0 0 0 15 0 0 0 0 0 21 0 0 0 0 0 0 0 29
If A is not sorted, then replace A(1):A(end) with min(A):max(A)
  1 件のコメント
Gillean
Gillean 2024 年 1 月 29 日
Hi, thanks a lot!! This is really nice and simple method, really appreciate it! :)

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

その他の回答 (1 件)

Rishi
Rishi 2024 年 1 月 29 日
Hi Gillean,
I understand from your query that you want to modify your array such that the missing numbers between two elements are replaced by '0'.
You can preallocate an array of 0s the required size. Then, using a loop, you can calculate the number of 0s required between two elements, and shift the second element by that difference.
Here is the code to implement the same:
A = [7, 15, 21, 29];
total_length = A(end) - A(1) + 1;
% Preallocate the padded array with zeros
padded_A = zeros(1, total_length);
padded_A(1) = A(1);
insert_index = 1;
for i = 1:length(A)-1
% Calculate the number of positions to move forward
insert_index = insert_index + (A(i+1) - A(i));
padded_A(insert_index) = A(i+1);
end
disp(padded_A);
7 0 0 0 0 0 0 0 15 0 0 0 0 0 21 0 0 0 0 0 0 0 29
Hope this helps!
  1 件のコメント
Gillean
Gillean 2024 年 1 月 29 日
Hi, thanks so much this works wonderfully! Appreciate the code as it goes through the process nicely, cheers!

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by