Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Can anyone tell me how I would work this out manually?
Consider the following MATLAB function:
function Anew = mystery( A )
N=5;
for ii=2:N
Anew(ii)= A(ii-1);
end
end
If we define v = [0,1,2,3,4,5,6,7,8,9,10]. What would be the output of x = mystery(v) be?
a) x = [1 2 3 4 5 6 7 8 9 10]
b) x = [1 2 3 4 5 6]
c) x = [0 1 2 3 4 5]
d) x = [0 0 1 2 3]
OK, let's step through this code line by line.
The first line:
N = 5;
This basically creates a variable called N and stores the value of 5 in it. No biggie.
Next line:
for ii = 2 : N
This is a for loop, and each time the loop iterates, the value of ii will change by 1. The first time the loop runs, ii = 2, then the next time it starts again, ii = 3 up to ii = 5, then the loop stops.
So, let's start at the beginning with ii = 2. The statement inside the loop is equivalent to:
Anew(2) = A(2-1);
This simplifies to:
Anew(2) = A(1);
If you look at the code, Anew was never defined up until this point. When you try to assign a value to a location in an array that was not previously declared, MATLAB will fill up the values that are before the location of where you assigned to be zero automatically. As such, if you did:
Anew(8) = 9; %// For example
Anew would look like this:
Anew =
0 0 0 0 0 0 0 9
The 8th position has the value of 9, while the other positions before the 8th one are all zero. Therefore, by doing Anew(2) = A(1);, the first position of Anew is zero, while the second position of Anew gets the first value of A and puts it here. As such, Anew currently looks like:
Anew =
0 0
Let's do ii = 3. This means that in your loop, the statement simplifies to:
Anew(3) = A(3-1);
.... which is:
Anew(3) = A(2);
This means that the third position of Anew gets the second element of A copied over here. Note that the original size of Anew was 2. By doing Anew(3) = A(2);, MATLAB will automatically adjust the size of Anew, and then put what A(2) is into the third position of Anew. Therefore, Anew looks like:
Anew =
0 0 1
As a little test, if we were to do Anew(6) = A(2);, this is what it would look like:
Anew =
0 0 0 0 0 1
Note that we previously had Anew = [0 0]; before this point. By doing Anew(6) = A(2);, the 3rd, 4th and 5th positions of Anew get filled with 0, and the 6th position gets the value of 1, which is A(2).
You can probably see a pattern now. Each position of Anew gets the element of A shifted to the left by 1. Therefore, for ii = 4:
Anew(4) = A(3);
What it looks like now is:
Anew =
0 0 1 2
Finally for ii = 5, we get:
Anew(5) = A(4);
What it looks like now is:
Anew =
0 0 1 2 3
After the end of this loop, Anew gets returned as the output of mystery.
Therefore, the answer is (d): x = [0 0 1 2 3];.
Hope this helps!
Related
i have the code and i try to make x as constraint but when i run i always get an error said that Undefined function or variable 'x'. below is the code and how can i get the sum of the z value?
clc;
clear;
%sum sum sum sum(fik*djq*xij*xkq)
%i,k= facilities
%j,q= location
%f(i,k)= flow between facilities i and k
%d(j,q)= distance between locations j and q
%xij = 1 if facility i is assigned to location j and if otherwise, xij = 0
% Flow matrix: flow assigning facility i (column) to facility k (row)
f = [0 5 7 9;
5 0 4 6;
7 4 0 3;
9 6 3 0];
%Distance matrix: distance assigning location j (column) to location q (row)
d = [0 6 8 9;
6 0 5 1;
8 5 0 2;
9 1 2 0];
z= 0;
nf= 4;%no of facilities
nd= 4;%no of locations
for i=1:nf
for j=1:nf
for k=1:nd
for q=1:nd
z = min('z','sum(sum(f(i,k)*d(j,q)*x(i,j)*x(k,q)))');
%if x(i,j)==1;
%else x(k,q)==0;
end
end
end
end
%Constraints
%x as binary 0 1,
%x(i,j) = 1 if facility i is assigned to location j 0r otherwise, x(i,j) = 0
Constraints.constr1 = (x(i,j))==1;
%The first set of constraints requires that each facility gets exactly one
%location, that is for each facility, the sum of the location values
%corresponding to that facility is exactly one
Constraints.constr2 = sum(x,2) == 1;
%The second set of constraints are inequalities. These constraints specify
%that each office has no more than one facility in it.
Constraints.constr3 = sum(x,1) == 1;
disp (z);
are the constraint i code is wrong?
In the attached code, as I can see, you are using matrix x 4 times.
The first use is inside the for-loops and other 3 uses are the one-liners following the loops.
First of all, I suspect you have used function min() in a wrong way. As the arguments should not be characters. Remove '' and use the following line:
z = min(z,sum(sum(f(i,k)*d(j,q)*x(i,j)*x(k,q))));
Now, coming to your question, you have not told what are the contents of your matrix x, so the code doesn't know what value is stored at say, x(1,1) or x(2,3).
It is, therefore, expected to throw an error.
I have the following code and it is taking a very long time to go through it... I dont think its an infinite loop but it is as follows:
Y = zeros(1069,30658);
D1 = LagOp({0,1,1,1},'Lags',[0,1,2,1]);
for n = 2:30658;
for j = 2:1063
if filter(D1,Ret((D1.Degree + j),n),'Initial',Ret(2:D1.Degree,n)) < 0;
Y(j+3,n) = -1*Ret(j+3,n);
else
Y(j+3,n)=Ret(j+3,n) ;
end
end
end
Basically I want to flip the sign of the current element in the matrix if the previous 3 elements before it add up to being less than 0. Otherwise to leave it alone. Could it be the ... else statement causing the trouble here ?
Edited: I figured out a more efficient way but I am working on figuring out how to change it to 3 values ahead instead with the following code:
for n = 1:30658
Y(:,n) = RET(:,n);
t = conv(Y(:,n), [1 1 1], 'valid');
mask = [false(3,1); t(1:end-1)<0];
Y(mask,n) = -Y(mask,n);
end`
So So for example, if I have a some numbers in an array given by -1 -2 -3 -4 -5 -6 -1 -2 3 -2 -1, then at the number -4 it would look at the sum of the previous 3 values (-1 - 2 - 3 < 0) and then change the sign of the value 3 ahead so -1 becomes positive and this would continue but the change in signs will not having any affect on the sums iterating for every row.
Thanks,
I'm trying to elegantly split a vector. For example,
vec = [1 2 3 4 5 6 7 8 9 10]
According to another vector of 0's and 1's of the same length where the 1's indicate where the vector should be split - or rather cut:
cut = [0 0 0 1 0 0 0 0 1 0]
Giving us a cell output similar to the following:
[1 2 3] [5 6 7 8] [10]
Solution code
You can use cumsum & accumarray for an efficient solution -
%// Create ID/labels for use with accumarray later on
id = cumsum(cut)+1
%// Mask to get valid values from cut and vec corresponding to ones in cut
mask = cut==0
%// Finally get the output with accumarray using masked IDs and vec values
out = accumarray(id(mask).',vec(mask).',[],#(x) {x})
Benchmarking
Here are some performance numbers when using a large input on the three most popular approaches listed to solve this problem -
N = 100000; %// Input Datasize
vec = randi(100,1,N); %// Random inputs
cut = randi(2,1,N)-1;
disp('-------------------- With CUMSUM + ACCUMARRAY')
tic
id = cumsum(cut)+1;
mask = cut==0;
out = accumarray(id(mask).',vec(mask).',[],#(x) {x});
toc
disp('-------------------- With FIND + ARRAYFUN')
tic
N = numel(vec);
ind = find(cut);
ind_before = [ind-1 N]; ind_before(ind_before < 1) = 1;
ind_after = [1 ind+1]; ind_after(ind_after > N) = N;
out = arrayfun(#(x,y) vec(x:y), ind_after, ind_before, 'uni', 0);
toc
disp('-------------------- With CUMSUM + ARRAYFUN')
tic
cutsum = cumsum(cut);
cutsum(cut == 1) = NaN; %Don't include the cut indices themselves
sumvals = unique(cutsum); % Find the values to use in indexing vec for the output
sumvals(isnan(sumvals)) = []; %Remove NaN values from sumvals
output = arrayfun(#(val) vec(cutsum == val), sumvals, 'UniformOutput', 0);
toc
Runtimes
-------------------- With CUMSUM + ACCUMARRAY
Elapsed time is 0.068102 seconds.
-------------------- With FIND + ARRAYFUN
Elapsed time is 0.117953 seconds.
-------------------- With CUMSUM + ARRAYFUN
Elapsed time is 12.560973 seconds.
Special case scenario: In cases where you might have runs of 1's, you need to modify few things as listed next -
%// Mask to get valid values from cut and vec corresponding to ones in cut
mask = cut==0
%// Setup IDs differently this time. The idea is to have successive IDs.
id = cumsum(cut)+1
[~,~,id] = unique(id(mask))
%// Finally get the output with accumarray using masked IDs and vec values
out = accumarray(id(:),vec(mask).',[],#(x) {x})
Sample run with such a case -
>> vec
vec =
1 2 3 4 5 6 7 8 9 10
>> cut
cut =
1 0 0 1 1 0 0 0 1 0
>> celldisp(out)
out{1} =
2
3
out{2} =
6
7
8
out{3} =
10
For this problem, a handy function is cumsum, which can create a cumulative sum of the cut array. The code that produces an output cell array is as follows:
vec = [1 2 3 4 5 6 7 8 9 10];
cut = [0 0 0 1 0 0 0 0 1 0];
cutsum = cumsum(cut);
cutsum(cut == 1) = NaN; %Don't include the cut indices themselves
sumvals = unique(cutsum); % Find the values to use in indexing vec for the output
sumvals(isnan(sumvals)) = []; %Remove NaN values from sumvals
output = {};
for i=1:numel(sumvals)
output{i} = vec(cutsum == sumvals(i)); %#ok<SAGROW>
end
As another answer shows, you can use arrayfun to create a cell array with the results. To apply that here, you'd replace the for loop (and the initialization of output) with the following line:
output = arrayfun(#(val) vec(cutsum == val), sumvals, 'UniformOutput', 0);
That's nice because it doesn't end up growing the output cell array.
The key feature of this routine is the variable cutsum, which ends up looking like this:
cutsum =
0 0 0 NaN 1 1 1 1 NaN 2
Then all we need to do is use it to create indices to pull the data out of the original vec array. We loop from zero to max and pull matching values. Notice that this routine handles some situations that may arise. For instance, it handles 1 values at the very beginning and very end of the cut array, and it gracefully handles repeated ones in the cut array without creating empty arrays in the output. This is because of the use of unique to create the set of values to search for in cutsum, and the fact that we throw out the NaN values in the sumvals array.
You could use -1 instead of NaN as the signal flag for the cut locations to not use, but I like NaN for readability. The -1 value would probably be more efficient, as all you'd have to do is truncate the first element from the sumvals array. It's just my preference to use NaN as a signal flag.
The output of this is a cell array with the results:
output{1} =
1 2 3
output{2} =
5 6 7 8
output{3} =
10
There are some odd conditions we need to handle. Consider the situation:
vec = [1 2 3 4 5 6 7 8 9 10 11 12 13 14];
cut = [1 0 0 1 1 0 0 0 0 1 0 0 0 1];
There are repeated 1's in there, as well as a 1 at the beginning and end. This routine properly handles all this without any empty sets:
output{1} =
2 3
output{2} =
6 7 8 9
output{3} =
11 12 13
You can do this with a combination of find and arrayfun:
vec = [1 2 3 4 5 6 7 8 9 10];
N = numel(vec);
cut = [0 0 0 1 0 0 0 0 1 0];
ind = find(cut);
ind_before = [ind-1 N]; ind_before(ind_before < 1) = 1;
ind_after = [1 ind+1]; ind_after(ind_after > N) = N;
out = arrayfun(#(x,y) vec(x:y), ind_after, ind_before, 'uni', 0);
We thus get:
>> celldisp(out)
out{1} =
1 2 3
out{2} =
5 6 7 8
out{3} =
10
So how does this work? Well, the first line defines your input vector, the second line finds how many elements are in this vector and the third line denotes your cut vector which defines where we need to cut in our vector. Next, we use find to determine the locations that are non-zero in cut which correspond to the split points in the vector. If you notice, the split points determine where we need to stop collecting elements and begin collecting elements.
However, we need to account for the beginning of the vector as well as the end. ind_after tells us the locations of where we need to start collecting values and ind_before tells us the locations of where we need to stop collecting values. To calculate these starting and ending positions, you simply take the result of find and add and subtract 1 respectively.
Each corresponding position in ind_after and ind_before tell us where we need to start and stop collecting values together. In order to accommodate for the beginning of the vector, ind_after needs to have the index of 1 inserted at the beginning because index 1 is where we should start collecting values at the beginning. Similarly, N needs to be inserted at the end of ind_before because this is where we need to stop collecting values at the end of the array.
Now for ind_after and ind_before, there is a degenerate case where the cut point may be at the end or beginning of the vector. If this is the case, then subtracting or adding by 1 will generate a start and stopping position that's out of bounds. We check for this in the 4th and 5th line of code and simply set these to 1 or N depending on whether we're at the beginning or end of the array.
The last line of code uses arrayfun and iterates through each pair of ind_after and ind_before to slice into our vector. Each result is placed into a cell array, and our output follows.
We can check for the degenerate case by placing a 1 at the beginning and end of cut and some values in between:
vec = [1 2 3 4 5 6 7 8 9 10];
cut = [1 0 0 1 0 0 0 1 0 1];
Using this example and the above code, we get:
>> celldisp(out)
out{1} =
1
out{2} =
2 3
out{3} =
5 6 7
out{4} =
9
out{5} =
10
Yet another way, but this time without any loops or accumulating at all...
lengths = diff(find([1 cut 1])) - 1; % assuming a row vector
lengths = lengths(lengths > 0);
data = vec(~cut);
result = mat2cell(data, 1, lengths); % also assuming a row vector
The diff(find(...)) construct gives us the distance from each marker to the next - we append boundary markers with [1 cut 1] to catch any runs of zeros which touch the ends. Each length is inclusive of its marker, though, so we subtract 1 to account for that, and remove any which just cover consecutive markers, so that we won't get any undesired empty cells in the output.
For the data, we mask out any elements corresponding to markers, so we just have the valid parts we want to partition up. Finally, with the data ready to split and the lengths into which to split it, that's precisely what mat2cell is for.
Also, using #Divakar's benchmark code;
-------------------- With CUMSUM + ACCUMARRAY
Elapsed time is 0.272810 seconds.
-------------------- With FIND + ARRAYFUN
Elapsed time is 0.436276 seconds.
-------------------- With CUMSUM + ARRAYFUN
Elapsed time is 17.112259 seconds.
-------------------- With mat2cell
Elapsed time is 0.084207 seconds.
...just sayin' ;)
Here's what you need:
function spl = Splitting(vec,cut)
n=1;
j=1;
for i=1:1:length(b)
if cut(i)==0
spl{n}(j)=vec(i);
j=j+1;
else
n=n+1;
j=1;
end
end
end
Despite how simple my method is, it's in 2nd place for performance:
-------------------- With CUMSUM + ACCUMARRAY
Elapsed time is 0.264428 seconds.
-------------------- With FIND + ARRAYFUN
Elapsed time is 0.407963 seconds.
-------------------- With CUMSUM + ARRAYFUN
Elapsed time is 18.337940 seconds.
-------------------- SIMPLE
Elapsed time is 0.271942 seconds.
Unfortunately there is no 'inverse concatenate' in MATLAB. If you wish to solve a question like this you can try the below code. It will give you what you looking for in the case where you have two split point to produce three vectors at the end. If you want more splits you will need to modify the code after the loop.
The results are in n vector form. To make them into cells, use num2cell on the results.
pos_of_one = 0;
% The loop finds the split points and puts their positions into a vector.
for kk = 1 : length(cut)
if cut(1,kk) == 1
pos_of_one = pos_of_one + 1;
A(1,one_pos) = kk;
end
end
F = vec(1 : A(1,1) - 1);
G = vec(A(1,1) + 1 : A(1,2) - 1);
H = vec(A(1,2) + 1 : end);
I'm having a few issues getting MATLAB to do what I want.
say I have a matrix x = [1 2 3 4; 1 4 4 5; 6 4 1 4]
I'm trying to write code that will go through the matrix and change each 4 to a 5, so it modifies the input matrix
I've tried a few things:
while index <= numel(x)
if index == 4
index = 5;
end
index = index + 1;
end
for item = x
if item == 4
item = 5;
end
end
the simplest thing i tried was
for item = x
if item == 4
item = 5;
end
end
i noticed by looking at the workspace that the value of item did indeed change but the value of x (the matrix) stayed the same.
How do I get the output that i'm looking for?
If you just want to change all the 4s to 5s then:
x(x==4)=5
basically x==4 will result in a logical matrix with 1s everywhere there was a 4 in x:
[0 0 0 1
0 1 1 0
0 1 0 1]
We then use logical index to only affect the values of x where those 1s are and change them all to 5s.
If you wanted to do this using a loop (which I highly recommend against) then you can do this:
for index = 1:numel(x)
if x(index) == 4
x(index) = 5;
end
end
Short answer to achieve what you want:
x(x==4) = 5
Answer to why your code doesn't do what you expected:
You are changing the item to a 5. But that item is a new variable, it does not point to the same item in your matrix x. Hence the original matrix x remains unchanged.
This is half a question and half a challenge to the matlab gurus out there:
I'd like to have a function take in a logical array (false/true) and give the beginning and ending of all the contiguous regions containing trues, in a struct array.
Something like this:
b = getBounds([1 0 0 1 1 1 0 0 0 1 1 0 0])
should return
b = 3x1 struct array with fields:
beg
end
and
>> b(2)
ans =
beg: 4
end: 6
I already have an implementation, but I don't really know how to deal with struct arrays well so I wanted to ask how you would do it - I have to go through mat2cell and deal, and when I have to deal with much larger struct arrays it becomes cumbersome. Mine looks like this:
df = diff([0 foo 0]);
a = find(df==1); l = numel(a);
a = mat2cell(a',ones(1,l))
[s(1:l).beg] = deal(a{:});
b = (find(df==-1)-1);
b = mat2cell(b',ones(1,l))
[s(1:l).end] = deal(b{:});
I don't see why you are using mat2cell, etc. You are making too much of the problem.
Given a boolean row vector V, find the beginning and end points of all groups of ones in the sequence.
V = [1 0 0 1 1 1 0 0 0 1 1 0 0];
You get most of it from diff. Thus
D = diff(V);
b.beg = 1 + find(D == 1);
This locates the beginning points of all groups of ones, EXCEPT for possibly the first group. So add a simple test.
if V(1)
b.beg = [1,b.beg];
end
Likewise, every group of ones must end before another begins. So just find the end points, again worrying about the last group if it will be missed.
b.end = find(D == -1);
if V(end)
b.end(end+1) = numel(V);
end
The result is as we expect.
b
b =
beg: [1 4 10]
end: [1 6 11]
In fact though, we can do all of this even more easily. A simple solution is to always append a zero to the beginning and end of V, before we do the diff. See how this works.
D = diff([0,V,0]);
b.beg = find(D == 1);
b.end = find(D == -1) - 1;
Again, the result is as expected.
b
b =
beg: [1 4 10]
end: [1 6 11]
By the way, I might avoid the use of end here, even as a structure field name. It is a bad habit to get into, using matlab keywords as variable names, even if they are only field names.
This is what I went with:
df = diff([0 foo 0]);
s = struct('on',num2cell(find(df==1)), ...
'off',num2cell(find(df==-1)-1));
I forgot about num2cell and the nice behavior of struct with cell arrays.