I'm not understanding how for loops are expanded in state flow. I the chart below I'm attempting to break a 32-bit value into 8, 4-bit chunks and store them into an array. I'm expecting bits 32-29 to go in buf(1), bits 28-25 in buf(2), bits 24-21 in buf(3) and so on. However, it seems that bits 1-4 get stuffed into each element of buf. Why is this not working properly and what is the correct way to implement something like this?

 채택된 답변

Samar
Samar 2026년 5월 7일 9:24

0 개 추천

Hi John,
In your chart, the shift distance is computed using unsigned fixed‑point (fi) arithmetic (because i is an unsigned fi). That can cause the negative shift count you intend (right shift) to be type-promoted/wrapped instead of staying a proper negative integer, so the bitshift effectively behaves like “no meaningful shift,” and then bitand(..., 0xF) keeps returning the lowest nibble for every element. This is consistent with Stateflow fixed‑point promotion behavior and fixed‑point operation rules stated in the MathWorks Documentation links given here: https://www.mathworks.com/help/stateflow/ug/how-fixed-point-data-works-in-stateflow-charts.html
The method explained below can help:
Make the shift amount a built‑in signed integer (e.g., int32), or use built‑in integer loop indices so the shift count is not a fi.
value = uint32(hex2dec('12345678'));
for i = 0:7
sh = int32(28 - 4*i);
buf(i+1) = bitand(bitshift(value, -sh), uint32(15));
end
Negative shifts mean right shift, and this works reliably when the shift count is a proper signed built‑in numeric type.
You can refer the following MathWorks Documentation/MATLAB Central links for more understanding:
Hope this helps!
Regards,
Samar

댓글 수: 1

John
John 2026년 5월 7일 13:49
Thanks, that cleared some things up for me. It seemed like my main problem was that the index variable, i, was unsigned.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Decision Logic에 대해 자세히 알아보기

제품

릴리스

R2025b

태그

질문:

2026년 5월 4일 18:40

댓글:

2026년 5월 7일 13:49

Community Treasure Hunt

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

Start Hunting!

Translated by