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

2 次查看(过去 30 天)
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 个评论
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.
Mathieu
Mathieu 2024-2-12
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 个)

类别

Help CenterFile Exchange 中查找有关 Programmatic Model Editing 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by