How to check if two strings are equal in fortran? [duplicate] - string

This question already has an answer here:
Comparing two strings in Fortran
(1 answer)
Closed 3 years ago.
I want to check if two strings are equal and do some work.
character(len = 50) :: x, y ,z
x="amin"
y="amin"
if(llt(x, y)) then
z=x
end if
I wrote this but it just checks first character in my string.
How can i handle it?

In Fortran two strings can be compared via relational operations i.e. <, >, ==, /=, etc..
So in your case:
if ( x == y ) then
z = x
end if
The llt() function does something completly different:
The llt() function tests whether a string is lexically less than another string based on the ordering of the ASCII collating sequence.

Related

Concatenate three numbers together in MATLAB [duplicate]

This question already has answers here:
Return vector elements as a single integer
(2 answers)
Closed 7 years ago.
Suppose that we have these three numbers:
a=2;
b=3;
c=5;
I want concatenate these three numbers to have:
out = 235; %// (double variable not string)
How can i do this with and without (prefer this) converting it to string?
A more general approach that Dan's: If you have a vector v of digits, you can convert it into a single number by
v = [a,b,c]; %// [2,3,5]
out = v * (10.^( (numel(v)-1):-1:0 ) )'
In addition to Shai's solution, you can use a combination of num2str and str2num.
v = [a; b; c]; %// [2;3;5]
out = str2num(num2str(v)')
out =
235
Or the faster, but maybe harder to read alternative:
out = str2num(char('0'+v))
Now, if you have to do this many times, you can assign this to an anonymous function handle:
f = #(v) str2num(num2str(v(:))')
Now you can simply do f(v). This will work with both horizontal and vertical arrays, due to the use of (:).
Note that you can turn Shai's approach into a function handle too:
f = #(v) v*(10.^((numel(v)-1):-1:0))';

Error when take two numbers out of a string

I'm just playing around with Lua trying to make a calculator that uses string manipulation. Basically I take two numbers out of a string, then do something to them (+ - * /). I can successfully take a number out of x, but taking a number out of y always returns nil. Can anyone help?
local x = "5 * 75"
function calculate(s)
local x, y =
tonumber(s:sub(1, string.find(s," ")-1)),
tonumber(s:sub(string.find(s," ")+3), string.len(s))
return x * y
end
print(calculate(x))
You have a simple misplaced parenthesis, sending string.len to tonumber instead of sub.
local x, y =
tonumber(s:sub(1, string.find(s," ")-1)),
tonumber(s:sub(string.find(s," ")+3, string.len(s)))
You actually don't need the string.len, as end of string is the default value for sub if nothing is given.
EDIT:
You can actually do what you want to do way shorter by using string.match instead.
local x,y = string.match(s,"(%d+).-(%d+)")
Match looks for tries to match the string with the pattern given and returns the captured values, in this case the numbers. This pattern translates to "One or more digits, then as few as possible of any character, then one or more digits". %d is 1 digit, + means one or more. . means any character and - means as few as possible. The values within the parentheses are captured, which means that they are returned.

Haskell syntax error for where statement [duplicate]

This question already has an answer here:
Why shouldn't I mix tabs and spaces?
(1 answer)
Closed 6 years ago.
I'm writing some Haskell code to learn the language, and I've run into the syntax error:
Vec2.hs:33:27: parse error on input '='
The code I've written here is below. The error is pointing at the 2nd term in vec2Normalize iLength = ... I don't see the syntax error
-- Get the inverse length of v and multiply the components by it
-- Resulting in the normalized form of v
vec2Normalize :: Vec2 -> Vec2
vec2Normalize v#(x,y) = (x * iLength, y * iLength)
where length = vec2Length v
iLength = if length == 0 then 1 else (1 / length)
Some guessing involved since you don’t provide the complete code, but this error could indicate that your line iLength = ... is not properly indented; actually, that the iLength starts to the right of the length = on the line before.
Does your original file use tabs instead of spaces for indentation? If so, be aware that Haskell always interprets a tab as spanning 8 columns. So, e.g.,
<TAB>where length = ...
<TAB><TAB><SPACE><SPACE>iLength = ...
would be interpreted as
where length = ...
iLength = ...
thus causing the error, even though your editor might show the lines properly aligned if it uses 4-column tabs.
You are using tabs for indentation, so the second definition in the where clause is actually not aligned with the first one. Haskell uses a tab width of 8 spaces, which may be different from your editor, leading to problems like this where the code looks okay, but really isn't.
I strongly recommend that you configure your editor to use spaces only when working with Haskell code.

I am trying to display variable names and num2str representations of their values in matlab

I am trying to produce the following:The new values of x and y are -4 and 7, respectively, using the disp and num2str commands. I tried to do this disp('The new values of x and y are num2str(x) and num2str(y) respectively'), but it gave num2str instead of the appropriate values. What should I do?
Like Colin mentioned, one option would be converting the numbers to strings using num2str, concatenating all strings manually and feeding the final result into disp. Unfortunately, it can get very awkward and tedious, especially when you have a lot of numbers to print.
Instead, you can harness the power of sprintf, which is very similar in MATLAB to its C programming language counterpart. This produces shorter, more elegant statements, for instance:
disp(sprintf('The new values of x and y are %d and %d respectively', x, y))
You can control how variables are displayed using the format specifiers. For instance, if x is not necessarily an integer, you can use %.4f, for example, instead of %d.
EDIT: like Jonas pointed out, you can also use fprintf(...) instead of disp(sprintf(...)).
Try:
disp(['The new values of x and y are ', num2str(x), ' and ', num2str(y), ', respectively']);
You can actually omit the commas too, but IMHO they make the code more readable.
By the way, what I've done here is concatenated 5 strings together to form one string, and then fed that single string into the disp function. Notice that I essentially concatenated the string using the same syntax as you might use with numerical matrices, ie [x, y, z]. The reason I can do this is that matlab stores character strings internally AS numeric row vectors, with each character denoting an element. Thus the above operation is essentially concatenating 5 numeric row vectors horizontally!
One further point: Your code failed because matlab treated your num2str(x) as a string and not as a function. After all, you might legitimately want to print "num2str(x)", rather than evaluate this using a function call. In my code, the first, third and fifth strings are defined as strings, while the second and fourth are functions which evaluate to strings.

How do I put variable values into a text string in MATLAB?

I'm trying to write a simple function that takes two inputs, x and y, and passes these to three other simple functions that add, multiply, and divide them. The main function should then display the results as a string containing x, y, and the totals.
I think there's something I'm not understanding about output arguments. Anyway, here's my (pitiful) code:
function a=addxy(x,y)
a=x+y;
function b=mxy(x,y)
b=x*y;
function c=dxy(x,y)
c=x/y;
The main function is:
function [d e f]=answer(x,y)
d=addxy(x,y);
e=mxy(x,y);
f=dxy(x,y);
z=[d e f]
How do I get the values for x, y, d, e, and f into a string? I tried different matrices and stuff like:
['the sum of' x 'and' y 'is' d]
but none of the variables are showing up.
Two additional issues:
Why is the function returning "ans 3" even though I didn't ask for the length of z?
If anyone could recommend a good book for beginners to MATLAB scripting I'd really appreciate it.
Here's how you convert numbers to strings, and join strings to other things (it's weird):
>> ['the number is ' num2str(15) '.']
ans =
the number is 15.
You can use fprintf/sprintf with familiar C syntax. Maybe something like:
fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)
reading your comment, this is how you use your functions from the main program:
x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)
Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:
function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);
and call it simply as:
out = answer(x,y);
As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.
With respect to getting ans = 3 as an output, it is probably because you are not assigning the output from answer to a variable. If you want to get all of the output values, you will have to call answer in the following way:
[out1,out2,out3] = answer(1,2);
This will place the value d in out1, the value e in out2, and the value f in out3. When you do the following:
answer(1,2)
MATLAB will automatically assign the first output d (which has the value 3 in this case) to the default workspace variable ans.
With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.
I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.
>> a=['matlab','is','fun']
a =
matlabisfun
>> size(a)
ans =
1 11
In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.
To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.
>> a={'matlab','is','fun'}
a =
'matlab' 'is' 'fun'
>> size(a)
ans =
1 3
I was looking for something along what you wanted, but wanted to put it back into a variable.
So this is what I did
variable = ['hello this is x' x ', this is now y' y ', finally this is d:' d]
basically
variable = [str1 str2 str3 str4 str5 str6]

Resources