Assign values to an array based on an if statement from a larger array

Hi,
I have an 20 elements array (uint8) in which some elements can be '0' and I want to retrieve the first 8 values that are not '0' and assign them to another array (uint8).
I am constrained to using only slcilib blocks and submodules so the sorting option is not usable.
So far I have done something like this
However, it seems that the for loop never ends and I have to manually stop the model using ctrl + C.
Does anyone have an idea about this issue?

4 件のコメント

Ayush Singh
Ayush Singh 2024 年 2 月 12 日
Are you allowed to make use of S function to implement the above logic?
Mathieu
Mathieu 2024 年 2 月 12 日
I can but it should be the last possible implementation
Fangjun Jiang
Fangjun Jiang 2024 年 2 月 12 日
編集済み: Fangjun Jiang 2024 年 2 月 12 日
I would use the MATLAB Function block. On the other hand, I don't think you are using the For Iterator block correctly. Take a look at the doc and example model.
First of all, indeed, I was not using the for iterator as it should..
Then, I tried using the MATLAB function block, however the same problem is persisting which is how can I index my output array as it should only contain the first 8 values (that are not '0') of my input array?
At first I tried to do a for loop to go through my input array, then test the value with an if statement but I cannot think of a way to index the value to the output array without a for loop which is fully looping every time it is called (thus ovewritting previously stored elements).
I know that I am missing something but cannot say what, is there any way you can help me with that?
Down below is what I come up with:
inputArray = [0 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15 0 17 0 19];
outputArray = [0 0 0 0 0 0 0 0];
for i=1:1:length(inputArray)
if inputArray(i) > 0
for j=1:1:j<8
outputArray(j) = inputArray(i);
end
end
end
Warning: Colon operands must be real scalars.
The expected output for the above code should be:
outputArray = [1 3 5 7 9 11 13 15]
but instead I am having an empty array.
Thanks,

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

 採用された回答

Fangjun Jiang
Fangjun Jiang 2024 年 2 月 12 日
編集済み: Fangjun Jiang 2024 年 2 月 12 日
inputArray = [0 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15 0 17 0 19 0 0 20 0 0 21];
index=(inputArray~=0);
tempData=inputArray(index);
outputArray=tempData(1:8)
outputArray = 1×8
1 3 5 7 9 11 13 15

その他の回答 (0 件)

カテゴリ

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

製品

リリース

R2023b

質問済み:

2024 年 2 月 9 日

編集済み:

2024 年 2 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by