Conditional operator

Conditional operator

by Jorge Faria -
Number of replies: 3

Hi,

Can anyone help me with this please:

How can I get something like this In formula question:

if Art == 1

Ang = Ang1[Frame];

if Art == 2

Ang = Ang2[Frame]

if Art == 3

Ang = Ang3[Frame]

if Art == 4

Ang = Ang4[Frame]


Basically depending on the Art value I whant to atribute to the variable Ang a diferent value. I have been unable to do this with the conditional operator:

c = (a>b) ? (a-b) : ((b>a) ? (b-a) : 0);
Thanks



Average of ratings: -
In reply to Jorge Faria

Re: Conditional operator

by Dominique Bauer -
Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Plugin developers

Hello Jorge,

In this case, you can use the pick() function.

Try this example:

Random variables

art={1:5}; # The last element is not inluded.
frame={0:2};

Global variables

ang1=[1,10];
ang2=[2,20];
ang3=[3,30];
ang4=[4,40];
i = art - 1;   # Indexing always start at 0.
ang= pick(i, ang1[frame], ang2[frame], ang3[frame], ang4[frame]);

Main question text

art = {art}, frame = {frame}, ang = {ang}

Part 1 Answer

1 (or any other value)

You will get exactly the same if, instead of:

ang= pick(i, ang1[frame], ang2[frame], ang3[frame], ang4[frame]);

you use:

ang = i == 0 ? ang1[frame] : (i == 1 ? ang2[frame] : (i == 2 ? ang3[frame] : (i==3 ? ang4[frame] : ang1[frame] )));
Average of ratings: Useful (1)
In reply to Dominique Bauer

Re: Conditional operator

by Jorge Faria -
Thank you for the help Dominique

Can you please help me with this also:

I always get an error and i dont understant how to atribute diferent values to a vector like VelTronc:

for (k:[1:19]) {

kM = k+1;
kL = k-1;

VelTronc[kM] = (AngTronc[kM]-AngTronc[kL])/2;
}


And how to know the lenght of the vetor?

there is a ny funtion like:

size(VelTronc) or lenght(VelTronc)? because I cant find any reference to this
In reply to Jorge Faria

Re: Conditional operator

by Dominique Bauer -
Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Plugin developers

Hello Jorge,

Let's look at a simple example. Given a set of numbers, we must find a set of the averages of the k-1 and k + 1 numbers.

Global variables

# data       Given set of numbers:
#            [10, 11, 16, 20, 30]
# avgDiff    Set of the averages between k+1 and k-1 values in data:
#            [ (16-10)/2,  (20-11)/2,  (30-16)/2 ] =
#            [ 3, 4.5, 7 ]
# kp         k + 1
# km         k - 1

data = [10, 11, 16, 20, 30];
avgDiff = fill(3,0);

for (k:[1:4]) {
    kp = k + 1;
    km = k - 1; 
    avgDiff[km] = ( data[kp] - data[km] )/2;
}

Question text

{avgDiff[0]}, {avgDiff[1]}, {avgDiff[2]}
<br>
{=len(avgDiff)}

As expected, the above yields:

3, 4.5, 7
3

It is important to remember that the index of an array always starts at zero.

The len() function ↗ returns the length of an array, although you should already know it.


Average of ratings: Useful (1)