Simple problems with MATLAB - matlab

I have three questions:
1)
I want to compute the following using MATLAB:
11^2 + 13^2 + 15^2 + ... + 109^2 + 111^2
I have tried using:
x = [11^2 13^2 15^2 ... 109^2 111^2]
z = cum(single(x))
but I got an error...
2)
I want to display '2 sin/pix'... I tried:
tittle('2 sin/pix')
Can I represent the display without displaying it in figure?
3)
The Fibonacci series is given as follow:
1, 2, 3, 5, 8, 13, 21, ...
How can I write a script file to calculate and print out the n-th Fibonacci term for n>2, where n is input by the user.
This is what I've tried:
input('n: ')
z = cumsum(n)
fprintf('the series=%d')
but I received an error...

1)
sum([11:2:111].^2)
2) Depending on whether you want a title or a text in a figure:
text(.5,.5,'2 sin\pix', 'interpreter','tex')
title('2 sin\pix', 'interpreter','tex')
BTW, the ASCII symbol of π is: 227 (Press and hold ALT and type 227 on Windows)
3) Take a look at this page:
http://blogs.mathworks.com/loren/2006/05/17/fibonacci-and-filter/

In the first subquestion, maybe you just mean sum instead of cum ?
I would do it like this:
x = [11:2:111]
sum(x .^ 2)
The first line is a range, giving a vector of every other number from 11 to 111, the second does a per-element squaring in that vector and sums it.
For the second question, I'm not sure what you really want to do. How about:
disp('2 sin/pix')

To compute: 11^2+13^2+...+109^2+111^2, try:
sum((11:2:111).^2)
To display '2 sin/pix'), the command is 'title' not 'tittle':
title('2 sin/pix')
Is this homework?

Related

OR-Tools CP-SAT solver: count successive NewBoolVar occurrences

In a simple range I try to get the amount of successive assignments for a variable. The values should be between 6-12 or should be 0. For example in the case a hospital has 24 shifts and an employee should work between 6 and 12 hours or not at all.
# Build shifts
shifts = {}
for n in all_nurses:
for d in all_days:
for s in all_shifts:
shifts[(n, d, s)] = model.NewBoolVar('shift_n%id%is%i' % (n, d, s))
# Count successive occurrences
for e_count in all_nurses:
s_count = 0
while s_count < len(all_shifts):
model.Add(sum(shifts[e_count, s_count] for s in range(e_count, e_count + 6 == 6) #min
model.Add(sum(shifts[e_count, s_count] for s in range(e_count, e_count + 12 <= 12) #min
Unfortunately this doesn't work since it increases the value with only one, what would be the best approach to check if how many hours have been assigned and increase s_count with that value?
If you just want to constrain the sum, you should use this method
model.AddLinearExpressionInDomain(sum(bool_vars), cp_model.Domain.FromIntervals([0, 0], [6, 12]))
If you want to constrain the length of a sequence, you should look at the shift_scheduling example
In particular, the soft sequence constraint.
The idea is the following, for every starting point, you want to forbid 010, 0110, 01110, ..., 0111110 and 01111111111110 (0110 means work[start] is false, work[start + 1] is true, work[start + 2] is true, work[start + 3] is false.
To forbid a sequence, just add a nogood, that is a clause (or AddBoolOr containing the negation of the pattern.
in my example bool_or(work[start], work[start + 1].Not(), work[start + 2].Not(), work[start + 3]).
Loop over all starting points and all patterns. And pay attention to the boundary conditions.

Matlab compare 2 single column matrixes and give position

I'm making a GUI in matlab to calculate ideal shifting points for a racecar.
For this I need to compare 2 single column matrixes.
Fwheel1 =
1.0e+003 *
4.5433
4.6372
4.6770
4.6892
4.7235
4.8064
4.9451
5.0838
5.2300
5.3401
5.4864
5.5454
5.5046
5.4758
5.5028
5.5782
5.6183
5.6663
5.7380
5.8174
5.8940
5.9553
6.0364
6.1075
6.0904
5.9285
5.7654
5.5762
5.3498
5.1766
5.0548
4.8236
4.6538
Fwheel2 =
1.0e+003 *
3.5174
3.5901
3.6209
3.6304
3.6569
3.7211
3.8285
3.9358
4.0490
4.1343
4.2475
4.2932
4.2617
4.2393
4.2602
4.3186
4.3496
4.3868
4.4423
4.5038
4.5631
4.6105
4.6734
4.7284
4.7151
4.5898
4.4635
4.3170
4.1418
4.0077
3.9134
3.7344
3.6029
These are the 2 matrixes. Now what I want is to compare Fwheel1 with Fwheel2. I want to know at which position in the matrix Fwheel2 > Fwheel1.
So output needs to be for example 23.
I hope somebody can help me.
Kind regards
You can do this easily with find.
idx= find( Fwheel2 > Fwheel1);
If you just want the first one, or the first n, you can just
idx= find( Fwheel2 > Fwheel1,n);
for another method,
c=0;
for i=1:33
if Fwheel2(i)>Fwheel1(i)
c=c+1;
b[c]=i
end
end
in the b vector you have your answer

MATLAB, how to evaluate multiple indices in one line?

I don't know how to explain this better than by giving you an example.
Suppose I have the following array:
a = magic(6)
And then I take a 'slice' of that like this:
a(:,1)
It will print:
35
3
31
8
30
4
Now I want the first number, so I want to write:
a(:,1)(1)
Instead of:
b = a(:,1)
b(1)
Also, is there a way to do something like this (assignment and comparison, i.e. set b, then evaluate against it):
(b = a(:,1))(1)
Ok, here's an update with a function where it isn't trivial to use a(1, 1)
come_on = sprintf('%i, ', magic(3));
come_on(1:end-2)
8, 3, 4, 1, 5, 9, 6, 7, 2
Also, what if I only want the first 4 numbers on magic(3)?
It would be better to write
sprintf('%i, ', magic(3)(1:4))(1:end-2)
instead of tens of lines, MHO.
You cannot concatenate indexing as foo(1)(2)(3). However, you can index multiple dimensions at once. So in this case, a(1,1) will give you what you want.

Arrange data using loop in MATLAB

If I have:
t=(1:1:5)'
time=1:3:100
How do I arrange data t in each column starting from 1 until the end, with an interval of 3. Which means that the data t (1 to 5) at column 1,4,7 and so on.
I've tried:
t=[1:1:5];
nt=length(temp);
time=[1:1:100];
nti=length(time);
x=zeros(nt,nti);
temp=temp';
initiator=2;
monomer=3;
post=1:3:100;
for l=1:post
step=1;
maxstep=100;
while (step<maxstep)
step=step+3;
temp=(1:1:5)';
end
t(:,l)=t;
x=[t];
end
This only shows result X with temp at column 1. I do not know how to to arrange this data at columns that I want.
Hope someone will help me. Thank you in advance.
How many dimensions does your data have? If you already have "temp" (temperature?) and "time" as your first two dimensions and you want "t" to be the third dimension, then create a three-dimension matrix.
To extract from indexes [1 4 7 10 13 16 ... ], use (1:3:end)
To extract from indexed [2 5 8 11 14 17 ... ], use (2:3:end)
In MATLAB's colon notation, the first value is the start. Second value is increment. Third value is the end value and is inclusive.

perfect hash function

I'm attempting to hash the values
10, 100, 32, 45, 58, 126, 3, 29, 200, 400, 0
I need a function that will map them to an array that has a size of 13 without causing any collisions.
I've spent several hours thinking this over and googling and can't figure this out. I haven't come close to a viable solution.
How would I go about finding a hash function of this sort? I've played with gperf, but I don't really understand it and I couldn't get the results I was looking for.
if you know the exact keys then it is trivial to produce a perfect hash function -
int hash (int n) {
switch (n) {
case 10: return 0;
case 100: return 1;
case 32: return 2;
// ...
default: return -1;
}
}
Found One
I tried a few things and found one semi-manually:
(n ^ 28) % 13
The semi-manual part was the following ruby script that I used to test candidate functions with a range of parameters:
t = [10, 100, 32, 45, 58, 126, 3, 29, 200, 400, 0]
(1..200).each do |i|
t2 = t.map { |e| (e ^ i) % 13 }
puts i if t2.uniq.length == t.length
end
On some platforms (e.g. embedded), modulo operation is expensive, so % 13 is better avoided. But AND operation of low-order bits is cheap, and equivalent to modulo of a power-of-2.
I tried writing a simple program (in Python) to search for a perfect hash of your 11 data points, using simple forms such as ((x << a) ^ (x << b)) & 0xF (where & 0xF is equivalent to % 16, giving a result in the range 0..15, for example). I was able to find the following collision-free hash which gives an index in the range 0..15 (expressed as a C macro):
#define HASH(x) ((((x) << 2) ^ ((x) >> 2)) & 0xF)
Here is the Python program I used:
data = [ 10, 100, 32, 45, 58, 126, 3, 29, 200, 400, 0 ]
def shift_right(value, shift_value):
"""Shift right that allows for negative values, which shift left
(Python shift operator doesn't allow negative shift values)"""
if shift_value == None:
return 0
if shift_value < 0:
return value << (-shift_value)
else:
return value >> shift_value
def find_hash():
def hashf(val, i, j = None, k = None):
return (shift_right(val, i) ^ shift_right(val, j) ^ shift_right(val, k)) & 0xF
for i in xrange(-7, 8):
for j in xrange(i, 8):
#for k in xrange(j, 8):
#j = None
k = None
outputs = set()
for val in data:
hash_val = hashf(val, i, j, k)
if hash_val >= 13:
pass
#break
if hash_val in outputs:
break
else:
outputs.add(hash_val)
else:
print i, j, k, outputs
if __name__ == '__main__':
find_hash()
Bob Jenkins has a program for this too: http://burtleburtle.net/bob/hash/perfect.html
Unless you're very lucky, there's no "nice" perfect hash function for a given dataset. Perfect hashing algorithms usually use a simple hashing function on the keys (using enough bits so it's collision-free) then use a table to finish it off.
Just some quasi-analytical ramblings:
In your set of numbers, eleven in all, three are odd and eight are even.
Looking at the simplest forms of hashing - %13 - will give you the following hash values:
10 - 3,
100 - 9,
32 - 6,
45 - 6,
58 - 6,
126 - 9,
3 - 3,
29 - 3,
200 - 5,
400 - 10,
0 - 0
Which, of course, is unusable due to the number of collisions. Something more elaborate is needed.
Why state the obvious?
Considering that the numbers are so few any elaborate - or rather, "less simple" - algorithm will likely be slower than either the switch statement or (which I prefer) simply searching through an unsigned short/long vector of size eleven positions and using the index of the match.
Why use a vector search?
You can fine-tune it by placing the most often occuring values towards the beginning of the vector.
I assume the purpose is to plug in the hash index into a switch with nice, sequential numbering. In that light it seems wasteful to first use a switch to find the index and then plug it into another switch. Maybe you should consider not using hashing at all and go directly to the final switch?
The switch version of hashing cannot be fine-tuned and, due to the widely differing values, will cause the compiler to generate a binary search tree which will result in a lot of comparisons and conditional/other jumps (especially costly) which take time (I've assumed you've turned to hashing for its speed) and require space.
If you want to speed up the vector search additionally and are using an x86-system you can implement a vector search based on the assembler instructions repne scasw (short)/repne scasd (long) which will be much faster. After a setup time of a few instructions you will find the first entry in one instruction and the last in eleven followed by a few instructions cleanup. This means 5-10 instructions best case and 15-20 worst. This should beat the switch-based hashing in all but maybe one or two cases.
I did a quick check and using the SHA256 hash function and then doing modular division by 13 worked when I tried it in Mathematica. For c++ this function should be in the openssl library. See this post.
If you were doing a lot of hashing and lookup though, modular division is a pretty expensive operation to do repeatedly. There is another way of mapping an n-bit hash function into a i-bit indices. See this post by Michael Mitzenmacher about how to do it with a bit shift operation in C. Hope that helps.
Try the following which maps your n values to unique indices between 0 and 12
(1369%(n+1))%13