How can I compute the summation of an interval. I will use Matlab's code for eg.
data=[1;2;3;4;5;6;7;8;9;10;11;12]
I would like to perform this summation.
sum(1)=data(1)+data(2)+data(3)
sum(2)=data(4)+data(5)+data(6)
sum(3)=data(7)+(data(8)+data(9)
sum(4)=data(10)+data(11)+data(12)
How can I get about this? (Using for loop)
No for loop needed, if indeed this interval is constant like in your example:
Ans=sum(reshape(data,3,[]))
note that I reshape the vector data to a matrix that has the right number of columns, so the value 3 relates to the interval size you wanted...
Related
I'm currently working on implementing a gradient check function in which it requires to get certain index values from the result matrix. Could someone tell me how to get a group of values from the matrix?
To be specific, for a result matrx res with size M x N, I'll need to get element res(3,1), res(4,2), res(1,3), res(2,4)...
In my case, M is dimension and N is batch size and there's a label array whose size is 1xbatch_size, [3 4 1 2...]. So the desired values are res(label(:),1:batch_size). Since I'm trying to practice vectorization programming and it's better not using loop. Could someone tell me how to get a group of value without a iteration?
Cheers.
--------------------------UPDATE----------------------------------------------
The only idea I found is firstly building a 'mask matrix' then use the original result matrix to do element wise multiplication (technically called 'Hadamard product', see in wiki). After that just get non-zero element out and do the sum operation, the code in matlab should look like:
temp=Mask.*res;
desired_res=temp(temp~=0); %Note: the temp(temp~=0) extract non-zero elements in a 'column' fashion: it searches temp matrix column by column then put the non-zero number into container 'desired_res'.
In my case, what I wanna do next is simply sum(desired_res) so I don't need to consider the order of those non-zero elements in 'desired_res'.
Based on this idea above, creating mask matrix is the key aim. There are two methods to do this job.
Codes are shown below. In my case, use accumarray function to add '1' in certain location (which are stored in matrix 'subs') and add '0' to other space. This will give you a mask matrix size [rwo column]. The usage of full(sparse()) is similar. I made some comparisons on those two methods (repeat around 10 times), turns out full(sparse) is faster and their time costs magnitude is 10^-4. So small difference but in a large scale experiments, this matters. One benefit of using accumarray is that it could define the matrix size while full(sparse()) cannot. The full(sparse(subs, 1)) would create matrix with size [max(subs(:,1)), max(subs(:,2))]. Since in my case, this is sufficient for my requirement and I only know few of their usage. If you find out more, please share with us. Thanks.
The detailed description of those two functions could be found on matlab's official website. accumarray and full, sparse.
% assume we have a label vector
test_labels=ones(10000,1);
% method one, accumarray(subs,1,[row column])
tic
subs=zeros(10000,2);
subs(:,1)=test_labels;
subs(:,2)=1:10000;
k1=accumarray(subs,1,[10, 10000]);
t1=toc % to compare with method two to check which one is faster
%method two: full(sparse(),1)
tic
k2=full(sparse(test_labels,1:10000,1));
t2=toc
Let A and B be two matrices of the same size. For a matrix M, let ht(M,t) threshold all the entries of M by t. That is All entries whose absolute value is less than t are set to 0. Suppose I want to find the optimal threshold t such that norm(ht(A,t)-B,'fro')^2 is minimized.
The only way that I can see to do this is deficient: do a for loop over the unique values of A and threshold A and setting C=ht(A,t)-B, compute sum(sum(C.*C)).
This is just too slow when A is large. I have considered sorting the elements of A and finding some efficient way to set a few entries to zero at a time, but I'm not sure this can all be done without a for loop.
Is there a way to do it?
Here's a very simple example (so simple a for loop works easily in this case):
B =
0.101508820368332 0
0 0.301996943246957
Set
A=B+.1*ones(2)
A =
0.201508820368332 0.1
0.1 0.401996943246957
Simple inspection shows that if we zero out the off-diagonal entries of A we minimize the difference between A and B. There are 3 possible threshold values, given by unique(A)=[.1,.2015,.402]. Given a potential threshold value t, we can hard threshold A by:
function [A_thresholded] = ht(A,t)
%
A_thresholded = A .* (abs(A)>t);
The form of the data in a matrix is irrelevant. You can convert them to vectors and simply compute the square-norm. In fact, you can sort the contents of A in increasing order (and permute B to preserve pairing). When you increase the threshold to include one more value in A, the norm only changes by that one increment. Therefore, you can find your solution in O(n log n). Hope this helps.
I have a 161*32 matrix (labelled "indpic") in MATLAB and I'm trying to find the frequency of a given number appearing in a row. So I think that I need to analyse each row separately for each value, but I'm incredibly unsure about how to go about this (I'm only new to MATLAB). This also means I'm incredibly useless with loops and whatnot as well.
Any help would be greatly appreciated!
If you want to count the number of times a specific number appears in each row, you can do this:
sum(indpic == val, 2)
where indpic is your matrix (e.g image) and val is the desired value to be counted.
Explanation: checking equality of each element with the value produces a boolean matrix with "1"s at the locations of the counted value. Summing each row (i.e summing along the 2nd dimension results in the desired column vector, where each element being equal to the number of times val is repeated in the corresponding row).
If you want to count how many times each value is repeated in your image, this is called a histogram, and you can use the histc command to achieve that. For example:
histc(indpic, 1:256)
counts how many times each value from 1 to 256 appears in image indpic.
Like this,
sum(indpic(rownum,:) == 7)
obviously change 7 to whatever.
You can just write
length(find(indpic(row_num,:)==some_value))
and it will give you the number of elements equal to "some_value" in the "row_num"th row in matrix "indpic"
I'd like to implement a piecewise periodic function, which should be zero in certain intervals and look like a test function elsewhere (e.g. exp(a^2/(abs(x)^2-a^2)) for abs(x)< a and zero otherwise).
I tried
nu = #(x) ((8*10^(-4)/exp(1)*exp(30^2./(abs(mod(x,365)-31).^2-30.^2))).* ...
and((1<mod(x,365)),(mod(x,365)<61)) + ...
(8*10^(-4)/exp(1)*exp(10^2./(abs(mod(x,365)-300).^2-10.^2))).* ...
and((290<mod(x,365)),(mod(x,365)<310)));
respectively
nu = #(x) ((0*x).* and((0<=mod(x,365)),(mod(x,365)<=1)) + ...
(8*10^(-4)/exp(1)*exp(30^2./(abs(mod(x,365)-31).^2-30.^2))).* ...
and((1<mod(x,365)),(mod(x,365)<61)) + ...
(0*x).* and((61<=mod(x,365)),(mod(x,365)<=290)) + ...
(8*10^(-4)/exp(1)*exp(10^2./(abs(mod(x,365)-300).^2-10.^2))).* ...
and((290<mod(x,365)),(mod(x,365)<310)) + ...
(0*x).* and((310<=mod(x,365)),(mod(x,365)<365)));
which should behave the same. The aim is to have a period of [0,365), therefore the modulo.
Now my problem is that nu(1)=nu(61)=nu(290)=nu(310)=NaN and also in a small neighborhood of them, e.g. nu(0.99)=NaN. But I excluded these points from the exponential function, where this one would cause problems. And even if I use a smaller interval for the exponential functions (e.g (2,60) and (291,309)) I receive NaN at the same points.
Any ideas? Thanks in advice!
One trick I use when performing vectorised calculations in which there's risk of a division by zero or related error is to use the conditional to modify the problem value. For instance, suppose you wanted to invert all entries in a vector, but leave zero at zero (and set any value within, say, 1e-8 to zero, too). You'd do this:
outVect = 1./(inVect+(abs(inVect)<=1e-8)).*(abs(inVect)>1e-8);
For values satisfying the condition that abs(value)>1e-8, this calculates 1/value. If abs(value)<=1e-8, it actually calculates 1/(value+1), then multiplies by zero, resulting in a zero value. Without the conditional inside the denominator, it would calculate 1/value when value is zero, resulting in inf... and then multiply inf by zero, resulting in NaN.
The same technique should work with your more complicated anonymous function.
I have an Nx2 matrix with columns as 'Time' and 'Progress'.
Progress is integral and Time is a real value corresponding to each progress unit.
I want to reverse the dependency and make 'Time' integral and output the fractional 'Progress' at every unit time step.
How can this be done?
Use interp1(Progress,Time,TimesWanted) where TimesWanted is a new vector with the times that you want. For example:
Progress=1:10; %just a guess of the sort of progress you might have
Time=Progress*5.5; %the resulting times (say 5.5s per step)
TimesWanted=10:5:50; %the times we want
interp1(Time,Progress,TimesWanted)
gives me:
ans =
1.8182 2.7273 3.6364 4.5455 5.4545 6.3636 7.2727 8.1818 9.0909
which is the progress at TimesWanted obtained by interpolation.