Scilab, get the last index of the maximum element in a vector - scilab

Given a vector, A=[1,2,10,10,10,1], [m,k]=max(A) returns k=3.
How to get the last index of the maximum element? In this example, I want to get 5.
The most succinct way I can think of is: [m,k]=max(A($:-1:1))
Is there a better way or does scilab provide a parameter to do this? Reversing a large vertex is not a good idea in any way.

Use the find command
You can use the find command to get all indices of the maximum:
indices = find(A==max(A))
last = max(indices)
Implement it yourself
Or if you want a single pass, you can implement it yourself:
//Create a c-function with your wanted behaviour
f1=['void max_array(int in_array[],int* in_num_elements,int *out_max, int *out_index)'
'{'
'int i;'
'*out_max=in_array[0];'
'*out_index=-1;'
'for (i=0; i<*in_num_elements; i++)'
'{'
'if(in_array[i]>=*out_max)'
'{'
'*out_max=in_array[i];'
'*out_index=i;'
'}'
'}'
'}'];
//Place it in a file in the current directory
mputl(f1,'max_array.c')
//Create the shared library (a gateway, a Makefile and a loader are
//generated.
ilib_for_link('max_array','max_array.c',[],"c")
//Load the library
exec loader.sce
//Create wrapper for readability
function [m,k] = last_max(vector)
[m, k] = call('max_array', vector, 1,'i', length(vector),2,'i', 'out',[1,1],3,'i',[1,1],4,'i');
// Because c is zero-indexed add 1
k = k + 1
endfunction
//Your data
A=[1,2,10,10,10,1];
//Call function on your data
[m,k] = last_max(A)
disp("Max value is " + string(m) + " at index " + string(k) )

Related

SCILAB - Undefined operation for the given operands

I am having a problem with scilab. At line "A=(f(a)+f(b))/2;" it gives me an error:
in builtin f
Undefined operation for the given operands.
check or define function %fptr_p_s for overloading.
Here are my codes:
function fx=f(x);
fx=4.*x^2.+3*exp^-x-4*cos*(1.5*x);
endfunction;
a=0;
b=2;
n=10; //sub interval
dx=(b-a)/n;
A=(f(a)+f(b))/2;
for k=1:(N-1)
A=A+f(a+k*dx);
end;
I=A*dx
fx = 4.*x^2. + 3*exp^-x - 4*cos*(1.5*x);
I guess you mean
fx = 4.*x^2. + 3*exp(-x) - 4*cos(1.5*x);
You can't put a function to a power, or multiply it by something.
You do that with its result, not with it.

How to count number of occurrences of a character in an array in Pascal

I have to script a pascal code that rations into calculation the frequency of a character's appearance in the code and displays it through the output mode
Input P2 changes:
Second Attempt at the coding phase
I tried revisioning the code.I added the output variable writeln('input array of characters'); & writeln('Number of Occurrences',k);, which should help me output how many times did the S character appear overall in the code, plus utilised the for & if commands to have the final values showcased based on the conditions, if the frequency is 1 then count in S, still getting errors, take a look at the Input P2 & Output P2
Input P1
function Count(t, s: String): Integer;
var
Offset, P: Integer;
begin
Result := 0;
Offset := 1;
P := PosEx(t, s, Offset);
while P > 0 do
begin
Inc(Result);
P := PosEx(t, s, P + 1);
end;
end;
Output P2
Target OS: Linux for x86-64
Compiling main.pas
main.pas(5,3) Error: Identifier not found "Result"
main.pas(7,8) Error: Identifier not found "PosEx"
main.pas(8,3) Error: Identifier not found "unsigned"
main.pas(8,12) Fatal: Syntax error, ";" expected but "identifier N" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
-------------------------------------------------------------------
Input P2
program p1
var S:string
i:integer
begin
writeln('input array of characters');
k:=O;
for i:=1 to length (S) do
if (S[i])='m') and (S[i+1]='a') then k:=k+1;
writeln('Number of Occurrences',k);
Readln;
end.
Output P2
Compiling main.pas
main.pas(2,1) Fatal: Syntax error, ";" expected but "VAR" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
The errors you see in the first block:
Identifier not found "Result"
Standard Pascal doesn't recognize the pseudovariable Result. In some Pascal implementations (like e.g. Delphi) it can be used to assign a value to the function result. The Pascal you are using needs to have the result of a function assigned to the name of the function. For example:
function Whatever(): integer;
begin
Whatever := 234;
end;
Identifier not found "PosEx"
Not all Pascal implementations include the PosEx() function. You need to use Pos() instead. But, the standard implementation of Pos() doesn't include the "search start position" that PosEx has. Therefore you need to ditch Pos() and do as you do in "Input P2", that is traverse the text character per character and count the occurances as you go.
Identifier not found "unsigned"
Seems you have removed that unknown identifier.
The error you see in the second block:
In Output P2 the error message should be clear. You are missing a semicolon where one is needed. Actually you are missing three of them.
You are also missing the line that reads user input: ReadLn(S);.
Finally, to calculate both upper and lower case characters you can use an extra string variable, say SU: string to which you assign SU := UpperCase(S) after reading user input, and then use that string to count the occurances.
I think this is more like what you want to do:
function Count(t, s: String): Integer;
var
Offset,Res, P: Integer;
begin
Res := 0
Offset := 1;
repeat
P := Pos(t, s, Offset);
if p>0 then
Inc(Res);
Offset := P+1
untl P = 0;
Count := Res;
end;
Now, if you don't have Pos, you can implement it:
Function Pos(const t,s:string; const Start:integer):Integer;
Var
LS, LT, {Length}
IxS, IxT, {Index)
R: Integer; {Result}
begin
R := 0;
{use only one of the two following lines of code}
{if your compiler has length}
LS := length(S); LT := Length(T);
{If it does not}
LS := Ord(s[0]); LT := Ord(T[0]);
if (LS <= LT) {if target is larger than search string, it's not there}
and (Start<=LT) and {same if starting position beyond size of S}
(Start+LT <-LS) then {same if search would go beyond size of S}
begin {Otherwise, start the search}
ixT := 1;
ixS := Start;
repeat
Inc(R); {or R:= R+1; if INC not available }
If (S[ixS] <> T[ixT]) then
R := 0 {they don't match, we're done}
else
begin {Move to next char}
Inc(ixS);
Inc(ixT);
end;
until (R=0) or (ixT>LT); {if search failed or end of target, done}
Pos := R;
end;

How do you access name of a ProtoField after declaration?

How can I access the name property of a ProtoField after I declare it?
For example, something along the lines of:
myproto = Proto("myproto", "My Proto")
myproto.fields.foo = ProtoField.int8("myproto.foo", "Foo", base.DEC)
print(myproto.fields.foo.name)
Where I get the output:
Foo
An alternate method that's a bit more terse:
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* myproto")
print(string.sub(fieldString, i + 2, j - (1 + string.len("myproto")))
EDIT: Or an even simpler solution that works for any protocol:
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* ")
print(string.sub(fieldString, i + 2, j - 1))
Of course the 2nd method only works as long as there are no spaces in the field name. Since that's not necessarily always going to be the case, the 1st method is more robust. Here is the 1st method wrapped up in a function that ought to be usable by any dissector:
-- The field is the field whose name you want to print.
-- The proto is the name of the relevant protocol
function printFieldName(field, protoStr)
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* " .. protoStr)
print(string.sub(fieldString, i + 2, j - (1 + string.len(protoStr)))
end
... and here it is in use:
printFieldName(myproto.fields.foo, "myproto")
printFieldName(someproto.fields.bar, "someproto")
Ok, this is janky, and certainly not the 'right' way to do it, but it seems to work.
I discovered this after looking at the output of
print(tostring(myproto.fields.foo))
This seems to spit out the value of each of the members of ProtoField, but I couldn't figure out the correct way to access them. So, instead, I decided to parse the string. This function will return 'Foo', but could be adapted to return the other fields as well.
function getname(field)
--First, convert the field into a string
--this is going to result in a long string with
--a bunch of info we dont need
local fieldString= tostring(field)
-- fieldString looks like:
-- ProtoField(188403): Foo myproto.foo base.DEC 0000000000000000 00000000 (null)
--Split the string on '.' characters
a,b=fieldString:match"([^.]*).(.*)"
--Split the first half of the previous result (a) on ':' characters
a,b=a:match"([^.]*):(.*)"
--At this point, b will equal " Foo myproto"
--and we want to strip out that abreviation "abvr" part
--Count the number of times spaces occur in the string
local spaceCount = select(2, string.gsub(b, " ", ""))
--Declare a counter
local counter = 0
--Declare the name we are going to return
local constructedName = ''
--Step though each word in (b) separated by spaces
for word in b:gmatch("%w+") do
--If we hav reached the last space, go ahead and return
if counter == spaceCount-1 then
return constructedName
end
--Add the current word to our name
constructedName = constructedName .. word .. " "
--Increment counter
counter = counter+1
end
end

Write a calculator for the identity sin² + cos² = 1

here's what I wrote:
public class Math {
public static void main (String[] args){
double degrees = Double.parseDouble(args[0]);
double s = Math.sin(degrees);
double c = Math.cos(degrees);
double x = s*s + c*s;
System.out.println(x);
}
}
I want to enter a number as args[0] that goes into sin() and cos(). then I want to add the 2 variables making it equal 1, because sin² + cos² = 1. What am I doing wrong?
EDIT: i made changes to my code to s*s + c*c, but i'm still getting the same error.
I'm also getting this error:
2 errors found:
File:... [line: 4]
Error: cannot find symbol
symbol: method sin(double)
location: class Math
File:... [line: 5]
Error: cannot find symbol
symbol: method cos(double)
location: class Math
You are not squaring each term so you are calculating and printing sin(x) + cos(x). Replace
double x = s + c;
with
double x = s*s + c*c;
and you should get the right behaviour.
Here's a list of what I see going wrong:
your class is called Math, but you're making a reference to the system's Math by using Math.sin() and Math.cos() -> rename your class to avoid the ambiguity
you define double x = s*s + c*s;, which should of course be double x = s*s + c*c;
you expect Math.cos() and Math.sin() to take their arguments in degrees, while they actually expect radians. It just happens to work because the identity holds for any input, but remember this for your next assignment :)

How to define a parameter recursively in GAMS?

I need to define a set of parameters that have a natural recursive relation.
Here is a MWE where I try to define the factorial function over a set of (nine) parameters S:
$title TitleOfProblem
set S / s1*s9 /;
alias(S, S1, S2);
set delta1(S1,S2);
delta1(S1,S2) = yes$(ord(S1) + 1 = ord(S2));
parameter f(S);
f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);
display f;
"delta1" is a relation containing pairs of elements in sorted order that differ by 1. Logically, the definition of f matches the definition of the factorial function (for inputs 1 to 9), but GAMS doesn't seem to like that f is defined recursively. The output of GAMS compilation looks something like this:
f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);
$141
141 Symbol neither initialized nor assigned
A wild shot: You may have spurious commas in the explanatory
text of a declaration. Check symbol reference list.
Question:
Is it possible to recursively define a parameter in GAMS? If not, what is a work-around?
(P.S. Someone with enough rep should create a tag "GAMS" and add it to this question.)
Someone showed me a solution for my example using a while loop. However, this solution is specific to factorial and does not generalize to an arbitrary recursive function.
$title factorial
set S / s1*s9 /;
parameter f(S);
parameter temp;
Loop(S,
temp=ord(s);
f(S)=ord(s);
While(temp > 1,
f(S) = f(S) * (temp-1);
temp = temp - 1;
);
);
display f;

Resources