Need to put a max value on my variable

6 ビュー (過去 30 日間)
Casi
Casi 2011 年 6 月 7 日
Currently, I am running a while loop with a distinct number of particles switching from one system to the other. However, I do not want more particles than the total number I started with. Is there a way to make a max value on a variable (say I started with 50 particles in A and 50 particles in B, I would never want more than 100 particles total.) Any help would be appreciated!
  3 件のコメント
Casi
Casi 2011 年 6 月 9 日
Sorry if I was unclear. I guess the point is that I have a bistable system with so many items in it. So, A is a vector with 50 elements in it. And all of those elements can jump between state A and B. However, as it is written now, if A has 100% chance of jumping into B, my code will just keep adding one more element to B without stopping even though it went above the amount I started with.
Fangjun Jiang
Fangjun Jiang 2011 年 6 月 9 日
I don't understand, even with your comments and two answers below.

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

回答 (3 件)

Walter Roberson
Walter Roberson 2011 年 6 月 9 日
There is no mechanism in MATLAB to declare a maximum size for a variable and to trigger an error when the size is exceeded.
You can approximate such a thing by creating a conditional breakpoint in the debugger -- e.g., have the breakpoint triggered if length(B) > 100

Kaustubha Govind
Kaustubha Govind 2011 年 6 月 9 日
Could you have your code call a helper function (say addOne) that saturates the value at 50? That seems like the simplest solution.
The only other alternative I can think of is to use the Fixed-Point Toolbox to define your own fixed-point type that only allows integer values in the range 0 through 50. (This would be a lot easier if your range were of the form 0 through (2^n) - 1, so you could represent it as an unsigned fixed-point type with n bits and zero fraction length)

Jason Ross
Jason Ross 2011 年 6 月 9 日
Would adding the number of elements in A and B (determined using size or length -- refer to the doc for exactly what these functions do) and checking the total was not equal to or greater than 100 solve your problem?
If you are doing it in a while loop, you would set this as your condition for continuing to run the loop.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by