How can I access to the index of a variable in 'for' loop - python-3.7

How do I access the index i and j in a for loop?
mu_1 = [1, 2, 3, 4]
mu_2 = [5, 6, 7, 8]
mu_3 = [9, 10, 11, 12]
mu_4 = [13, 14, 15, 16]
som = 0
for i in range(1, 4):
for j in range(i+1, 5):
r = (mu_i - mu_j)
som = som + r
I want to get this output:
som = ((mu_1 - mu_2) + (mu_1 - mu_3) + (mu_1 - mu_4) +
(mu_2 - mu_3) + (mu_2 - mu_4) +
(mu_3 - mu_4))

I think what you are trying to ask is how to use indices i and j to refer to your mu_n lists. As per the code below, you could add all lists into another list, and index into it.
However, you cannot subtract lists in Python.
Note! : This won't work because the - (subtraction) operation is not supported for list types.
mu = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
som = 0
for i in range(4):
for j in range(i+1, 4):
r = (mu[i] - mu[j])
som = som + r
Finally
You might benefit from knowing that indices in Python start from 0.

It is unclear what exactly you are trying to achieve, but you can use the enumerate function to iterate over an iterable together with its indices.
for i, x in enumerate([1, 5, 13, 6]):
# Here, `i` is the items index and `x` the item itself
pass

Related

Group and sum elements that are the same within a vector

Let's say I have a vector that looks as so (the numbers will always be > 0)...
[1, 2, 1, 4, 1, 2, 4, 3]
I need a vectorized implementation that sums the numbers together and uses the original number as the index to store the number. So if I run it I would get...
% step 1
[1+1+1, 2+2, 3, 4+4]
% step 2
[3, 4, 3, 8]
I have already implemented this using for loops, but I feel like there is a vectorized way to achieve this. I am still quite new at vectorizing functions so any help is appreciated.
This sounds like a job for accumarray:
v = [1, 2, 1, 4, 1, 2, 4, 3];
result = accumarray(v(:), v(:)).'
result =
3 4 3 8
Other approaches:
Using histcounts:
x = [1, 2, 1, 4, 1, 2, 4, 3];
u = unique(x);
result = u.*histcounts(x, [u inf]);
Using bsxfun (may be more memory-intensive):
x = [1, 2, 1, 4, 1, 2, 4, 3];
u = unique(x);
result = u .* sum(bsxfun(#eq, x(:), u(:).' ), 1);

Python quicksort only sorting first half

I'm taking Princeton's algorithms-divide-conquer course - 3rd week, and trying to implement the quicksort.
Here's my current implementation with some tests ready to run:
import unittest
def quicksort(x):
if len(x) <= 1:
return x
pivot = x[0]
xLeft, xRight = partition(x)
print(xLeft, xRight)
quicksort(xLeft)
quicksort(xRight)
return x
def partition(x):
j = 0
print('partition', x)
for i in range(0, len(x)):
if x[i] < x[0]:
n = x[j + 1]
x[j + 1] = x[i]
x[i] = n
j += 1
p = x[0]
x[0] = x[j]
x[j] = p
return x[:j + 1], x[j + 1:]
class Test(unittest.TestCase):
def test_partition_pivot_first(self):
arrays = [
[3, 1, 2, 5],
[3, 8, 2, 5, 1, 4, 7, 6],
[10, 100, 3, 4, 2, 101]
]
expected = [
[[2, 1, 3], [5]],
[[1, 2, 3], [5, 8, 4, 7, 6]],
[[2, 3, 4, 10], [100, 101]]
]
for i in range(0, len(arrays)):
xLeft, xRight = partition(arrays[i])
self.assertEqual(xLeft, expected[i][0])
self.assertEqual(xRight, expected[i][1])
def test_quicksort(self):
arrays = [
[1, 2, 3, 4, 5, 6],
[3, 5, 6, 10, 2, 4]
]
expected = [
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 6, 10]
]
for i in range(0, len(arrays)):
arr = arrays[i]
quicksort(arr)
self.assertEqual(arr, expected[i])
if __name__ == "__main__":
unittest.main()
so for array = [3, 5, 6, 10, 2, 4] I get [2, 3, 6, 10, 5, 4] as a result... I can't figure what's wrong with my code. It partitions just fine, but the results are off...
Can anyone chip in? :) Thank you!
it's actually so minor problem that you'd be laughing
the problem resides with quicksort function
the correct one is:
def quicksort(x):
if len(x) <= 1:
return x
pivot = x[0]
xLeft, xRight = partition(x)
print(xLeft, xRight)
quicksort(xLeft)
quicksort(xRight)
x=xLeft+xRight #this one!
return x
what happens is python created a new object out of these xleft and xright they were never an in place-sort
so this is one solution(which is not in place)
the other one is to pass the list,the start_index,end_index
and do it in place
well done fella!
edit:
and actually if you'd print xleft and xright you'd see it performed perfectly:)

Matrix dimensions must agree, Index exceeds matrix dimensions

I have the following code for positioning some subplots:
fig = figure;
fig.Units = 'centimeters';
fig.Position(3:4) = [25 25];
plotPositions = [ 3, 21, 7, 7;
12, 21, 7, 7;
];
nPlots=length(plotPositions); % shorthand variable for convenience
hAx=zeros(nPlots,1); % preallocate array for axes/subplot handles
for i = 1:length(plotPositions)
plotHandle = subplot(3, 2, i);
plotHandle.Units = 'centimeters';
plotHandle.Position = plotPositions(i,:);
hAx(i)=subplot(3, 2, i);
axis(hAx(i),[ -300 300 0 150]); %
end
If I use
plotPositions = [ 3, 21, 7, 7;
12, 21, 7, 7;
3, 12, 7, 7;
12, 12, 7, 7;
3, 3, 7, 7;
12, 3, 7, 7];
it works, but if use
plotPositions = [ 3, 21, 7, 7;
12, 21, 7, 7;
];
it does not work, and I'm getting the error:
Matrix dimensions must agree.
Index exceeds matrix dimensions.
What's going on?
You shouldn't be using the function length but instead the function size(...,1) to count the rows of plotPositions. length is actually max(size(vec)), which is 6 (number of rows, correctly) in the "working" case, and 4 (number of columns) in the non-working one.
Thus, in the 2nd case you're actually trying to access "nonexistent" rows, so MATLAB complains....

Average of neighbouring pairs 'interpolation'

I have two vectors, for example
A = [1, 3, 6, 7]
B = [2.0, 5.1, 2.2, 1]
I want to create a vector C and C1 so it would create the missing elements and assign to each of them the average of the corresponding surrounding elements in B.
C = [1, 2, 3, 4, 5, 6, 7]
C1 = [2.0, 3.55, 5.1, 3.65, 3.65, 2.2, 1]
What is the best way to that?
In order to use interp1 you would need
Ci = [1, 2, 3, 4.5, 4.5, 6, 7]
and then
C1 = interp1(A,B,Ci)
However generating that Ci is about as difficult as generating C1. I think in this case your best bet is to loop:
%// Assuming A is sorted
C = min(A):max(A);
C1 = zeros(size(C));
Acounter = 1;
for ii = 1:numel(C)
if C(ii)==A(Acounter)
C1(ii) = B(Acounter);
Acounter = Acounter + 1;
else
C1(ii) = (B(Acounter) + B(Acounter-1))/2;
end
end

Filling missing data in a data set

I have a data set like the following:
x= [1, 4, 10]
y= [10, 20, 30]
(x and y are value pairs, i.e. (1,10), (4,20), (10,30))
I would like to fill the x values gaps and get linear interpolated values for y. The linear interpolation should be done between each value pair, i.e. between (1,10) and (4,20) and then again between (4,20) and (10,30).
x= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y= [10,?, ?, 20, ?, ?, ?, ?, ?, 30]
How can I solve this with MATLAB?
Regards,
Dennis
P.S. My original data set has over 300 value pairs...
Using interp1
Code:
x= [1, 4, 10];
y= [10, 20, 30];
xi = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
yi = interp1(x,y,xi);
Results:
>> yi
yi =
10 13.333 16.667 20 21.667 23.333 25 26.667 28.333 30
Graphical Output using plot(xi,yi,'-*')