How can I assign to a variable an interval of numbers.
39 views (last 30 days)
Show older comments
For example, how do I assign a variable R5 to be equal to 1 <= R5 <=20. I tried doing this
R5 = (5 <= R5) && (R5 <= 60)
but it didn't work in my code. It showed an error on the command window when I ran the code
0 Comments
Answers (2)
John D'Errico
on 14 Jan 2023
Edited: John D'Errico
on 14 Jan 2023
You cannot just tell MATLAB that a normal variable is any value in some interval. Effectively, this requires interval arithmetic tools to make it work, and they get very complicated when you may have complicated functions. Even a divide, for example, can turn a finite interval into an infinite interval. And what starts out as a finite interval can easily turn into multiple disjoint intervals. (I do recall seeing an interval arithmetic toolbox available for MATLAB. It was not free as I recall, but a third party toolbox.)
However, you can use tools like linspace or the colon operator to create a list of points in some interval.
R5 = 5:20
or
R5 = linspace(5,20,10)
Don't forget to use the .* and ./ and .^ operators when you work with those vectors of elements.
In a symbolic context, can you define a variable to have specific limits? That does not always work as well as you might like, but you can do this:
syms R5
assume(5<=R5<=20)
assumptions
As you see, in theory, MATLAB knows that R5 has bounds. However, not all computations will make good use of those assumptions. But, for example, solve now finds only the root in the interval of interest.
solve(R5^2 - 12*R5 - 15 == 0)
0 Comments
Image Analyst
on 14 Jan 2023
If you want to say that the "x" axis are your indexes, so that x=1 at element 1, x=2 at element 2, and so on as far as you want to go, then you can for example have a number line of 80 x values
R5 = zeros(1, 80); % Zero outside of the specified range.
and then assign 1 to elements 5 through 60 like this
R5(5:60) = 1;
plot(R5, '.', 'MarkerSize', 12);
grid on;
0 Comments
See Also
Categories
Find more on Assumptions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!