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

5 views (last 30 days)
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 Comments
Fangjun Jiang
Fangjun Jiang on 12 Feb 2024
Edited: Fangjun Jiang on 12 Feb 2024
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 on 12 Feb 2024
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,

Sign in to comment.

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 12 Feb 2024
Edited: Fangjun Jiang on 12 Feb 2024
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

More Answers (0)

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!