Related
I have trying to multipy a column matrix and a row matrix in mathematica. But mathematica gives row matrix as a column matrix. so multipy function doesnt work. My codes are
`Y = Inverse[S];
Print["Y=", MatrixForm[Y]];
For[i = 1, i <= n, i++,
Subscript[P, i] = MatrixForm[S[[All, i]].Y[[i]]];
Print["CarpimS=", MatrixForm[S[[All, i]]]];
Print["CarpimY=", MatrixForm[Y[[i]]]];
Print["P=", Subscript[P, i]];
];
If anyone know this situation please answer
This is a badly written question, so I'm going to have to make some guesses. Your code does not seem relevant to your question, with this exception: S[[All, i]].Y[[i]]. Given your description, I'm guessing we can say that S is k by k and so is Y. If your goal is to Dot the i-th column of S by the i-th row of its inverse Y, then what you have is fine: you produce each as a 1-d vector, and then produce a scalar product. But you say you're not getting what you want, so I'm guessing you want the outer product instead.
mS = IdentityMatrix[5];
mS[[3, 3]] = 99;
mY = Inverse[mS];
mS[[All, 3]].mY[[3]] (* scalar product *)
Outer[Times, mS[[All, 3]], mY[[3]]] (* outer product *)
If I guessed wrong, you will have to work on improving your question.
I'm working on a color image segmentation in HSV color space using Matlab fuzzy toolbox.
the goal is to read an RGB image->convert to hsv->use H,S,V values as an input for fuzzy system and then find which class(here is our 16 constant output color) does this pixel belongs.
here is the fuzzy system :
"The reasoning procedure is based on a zero-order Takagi-Sugeno model, so that the consequent part of each fuzzy rule is a crisp discrete value of the set{Black, White, Red, Orange,etc}.
Since this model has 10 fuzzy sets for Hue, 5 for Saturation and 4 for Value, the total number of rules required for this model is 10*5*4=200".(1)
The problem is that when I use this line in my program to get output value
segimg=reshape(evalfis([h s v],hsvRuleSugeno),imgh,imgw);
the out put is not any of my constant classes, because it uses centroid for defuzzification and as you see below I can't rely on it, as an output !
I search many papers and websites but I think it's so simple that no one explained it! I'm missing something or probably i don't have enough knowledge would you please help me to understand this problem ?
reference:
(1): Human Perception-based Color Segmentation Using Fuzzy Logic,Lior Shamir Department of Computer Science, Michigan Tech.
The paper explains the computation process in section 2.3. You do not need non-discrete or centroid value as obtained from evalfis. I'm assuming you have made all the rules which must be giving one of the 16 classes as output. That means each each output class is associated with at least one rule. According to the paper, you need to:
Make 16 groups containing rules associated to each output class. One group for yellow, one for white and one for black so on...
Calculate the strength of each and every rule.
For each group, find summation of strength value of all the rules contained in that group.
Then find the group with maximum cumulative sum of strength of its contained rules.
To achieve this, we cannot rely on centroid based defuzzified value. I checked the documentation on evalfis and below is script that should be able to perform above algorithm. Idea is to collect strength of each rule, order the rules into groups based on rule's output class, then find summation of each group and find maximum.
[output, IRR, ORR, ARR] = evalfis(input, fismat)
m = cat(2, ORR, ARR);
m = sortrows(m, 1)
r = [];
for l = 2 : size(m, 1)
if m(l, 1) ~= m(l - 1, 1)
r = cat(1, r, m(l - 1, :));
else
m(l, 2) = m(l, 2) + m(l - 1, 2);
end
end
if size(m, 1) >= 2
r = cat(1, r, m(size(m, 1), :));
end
% r now contains the final class to be choosen
disp(r)
Thanks a lot for your answer Shivam,
Actually your code has an error but I got the idea and started working on it, and finally found what to do ! here is what I use and the result was OK ! now I have to work on adjusting rules to get better results
for i=1:imh
for j=1:imw
[output, IRR, ORR, ARR] = evalfis([h(i,j);s(i,j);v(i,j)], hsvRuleSugeno);
m = cat(2,ARR,ORR);
[trash,idx] = unique(m(:,1),'first');
out = m(sort(idx),:);
out(:,[1,2])=out(:,[2,1]);
out = sortrows(out, 1);
res=zeros(size(out));
for l = 2 : size(out, 1)
if out(l, 1) == out(l - 1, 1)
res(l-1,1) = out(l-1,1);
res(l-1,2) = out(l-1,2)+out(l,2);
else
res(l,1) = out(l,1);
res(l,2) = out(l,2);
end
end
[num idx] = max(res(:,2));
[x y] = ind2sub(size(res),idx);
segimg(i,j)=res(x,y)/10;
end
end
the segment result :http://i45.tinypic.com/2aj9mg.jpg
I'm very new to Mathematica, and I'm getting pretty frustrated with the errors I'm generating when it comes to creating a function. Below, I have a function I'm writing for 'centering' a matrix where rows correspond to examples, columns to features. The aim is to subtract from each element the mean of the column to which it belongs.
centerdata[datamat_] := (
numdatapoints =
Dimensions[datamat][[1]](*Get number of datapoints*)
numberfeatures =
Dimensions[datamat[[1]]][[1]](*Get number of datapoints*)
columnmean = ((Total[datamat])/numdatapoints)
For[i = 1, i < numdatapoints + 1, i++, (* For each row*)
For[j = 1, j < numfeatures + 1, j++, (* For each element*)
datum = datamat[[i]][[j]];
newval = (datum - (colmean[[j]]));
ReplacePart[datamat, {i, j} -> newval];
];
];
Return[datamat];
)
Running this function for a matrix, I get the following error:
"Set::write: Tag Times in 4 {5.84333,3.054,3.75867,1.19867} is Protected. >>
Set::write: "Tag Times in 4\ 150 is Protected."
Where {5.84333,3.054,3.75867,1.19867} is the first example in the data matrix and 150 is the number of examples in the matrix (I'm using the famous iris dataset, for anyone interested). These errors correspond to this code:
numdatapoints = Dimensions[datamat][[1]](*Get number of datapoints*)
numberfeatures = Dimensions[datamat[[1]]][[1]](*Get number of datapoints*)
Googling and toying with this error hasn't helped much as the replies in general relate to multiplication, which clearly isn't being done here.
Given a table (tab) of data the function Mean[tab] will return a list of the means of each column. Next, you want to subtract this (element-wise) from each row in the table, try this:
Map[Plus[-Mean[tab],#]&,tab]
I have a feeling that there is probably either an intrinsic statistical function to do this in one statement or that I am blind to a much simpler solution.
Since you are a beginner I suggest that you immediately read the documentation for:
Map, which is one of the fundamental operators in functional programming languages such as Mathematica pretends to be; and
pure functions whose use involves the cryptic symbols # and &.
If you are writing loops in Mathematica programs you are almost certainly mis-using the system.
My question sounds more general, but I have a specific example. I have a list of data in form:
plotDataAll={{DateList1, integerValue1}, {DateList2, integerValue2}...}
The dates are sorted chronologically, that is plotDataAll[[2,1]] is a more recent time then plotDataAll[[1,1]].
I want to create plots of specific periods, 24h ago, 1 week ago, etc. For that I need just a portion of data. Here's how I got what I wanted:
mostRecentDate=Max[Map[AbsoluteTime, plotDataAll[[All,1]]]];
plotDataLast24h=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-86400.)&];
plotDataLastWeek=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-604800.)&];
plotDataLastMonth=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-2.592*^6)&];
plotDataLast6M=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-1.5552*^7)&];
Then I used DateListPlot to plot the data. This becomes slow if you need to do this for many sets of data.
What comes to my mind, if I could find the index of first element in list that satisfies the date condition, because it's chronologically sorted, the rest of them should satisfy the condition as well. So I would have:
plotDataLast24h=plotDataAll[[beginningIndexThatSatisfiesLast24h;;Length[plotDataAll]]
But how do I get the index of the first element that satisfies the condition?
If you have a faster way to do this, please share your answer. Also, if you have a simple, faster, but sub-optimal solution, that's fine too.
EDIT:
Time data is not in regular intervals.
If your data is at regular intervals you should be able to know how many elements constitute a day, week, etc. and use Part.
plotDataAll2[[knownIndex;;-1]]
or more specifically if the data was hourly:
plotDataAll2[[-25;;-1]]
would give you the last 24 hours. If the spacing is irregular then use Select or Pick. Date and time functions in Mma are horrendously slow unfortunately. If you are going to do a lot of date and time calculation better to do a conversion to AbsoluteTime just once and then work with that. You will also notice that your DateListPlots render much faster if you use AbsoluteTime.
plotDataAll2=plotDataAll;
plotDataAll2[[All,1]]=AbsoluteTime/#plotDataAll2[[All,1]];
mostRecentDate=plotDataAll2[[-1,1]]
On my computer Pick is about 3 times faster but there may be other improvements you can make to the code below:
selectInterval[data_, interval_] := (tmp = data[[-1, 1]] - interval;
Select[data, #[[1]] > tmp &])
pickInterval[data_, interval_] := (tmp = data[[-1, 1]] - interval;
Pick[data, Sign[data[[All, 1]] - tmp], 1])
So to find data within the last week:
Timing[selectInterval[plotDataAll2, 604800]]
Timing[pickInterval[plotDataAll2, 604800]]
The thing that you want to avoid is checking all the values in the data table. Since the data is sequential you can just start checking from the back and stop when you have found the correct index.
Schematically:
tab = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
i = j = Length#tab;
While[tab[[i]] > 5, --i];
tab[[i ;; j]]
-> {5, 6, 7, 8, 9}
sustitute > 5 for whatever you want to check for. I didn't have time to test this right now but in your case, e.g.,
maxDate=AbsoluteTime#plotDataAll[[-1,1]]; (* no need to find Max if data is sequential*)
i24h = iWeek = iMonth = iMax = Length#plotDataAll;
While[AbsoluteTime#plotDataAll[[i24h,1]] > maxDate-86400.,--i24h];
While[AbsoluteTime#plotDataAll[[iWeek,1]] > maxDate-604800.,--iWeek];
While[AbsoluteTime#plotDataAll[[iMonth,1]] > maxDate-2.592*^6.,--iMonth];
While[AbsoluteTime#plotDataAll[[i6Month,1]] > maxDate-1.5552*^7.,--i6Month];
Then, e.g.,
DateListPlot#plotDataAll[[i24h;;iMax]]
If you want to start somewhere in the middle of plotDataAll just use a While to first find the starting point and set iMax and maxDate apropriately.
For large data sets this may be one of the few instances where a loop construct is better than MMA's inbuilt functions. That, however, may be my own ignorance and if anyone here knows of a MMA inbuilt function that does this sort of "stop when match found" comparison better than While.
EDIT: Timing comparisons
I played around a bit with Mike's and my solution and compared it to the OP's method. Here is the toy code I used for each solution
tab = Range#1000000;
(* My solution *)
i = j = tab[[-1]];
While[tab[[i]] > j - 24, --i];
tab[[i ;; j]]
(* Mike's solution *)
tmp = tab[[-1]] - 24;
Pick[tab, Sign[tab[[All]] - tmp], 1]
(* Enedene's solution *)
j = tab[[-1]];
Select[tab, # > (j - 24) &]
Here are the results (OS X, MMA 8.0.4, Core2Duo 2.0GHz)
As you can see, Mike's solution has a definite advantage over enedene's solution but, as I surmised originally, the downside of using inbuilt functions like Pick is that they still perform a comparative check on all the element in a list which is highly superfluous in this instance. My solution has constant time due to the fact that no unneccessary checks are made.
I have to solve a system of non-linear equations for a wide range of parameter space. I'm using FindRoot, which is sensitive to initial start point so I have to do it by hand and by trial and error and plotting, rather than putting the equations in a loop or in a table.
So what I want to do is create a database or a Matrix with a fixed number of columns but variable number of rows so I can keep appending it with new results as and when I solve for them.
Right now I've used something like:
{{{xx, yy}} = {x, y} /. FindRoot[{f1(x,y) == 0,f2(x,y)==0}, {x,a},{y,b}],
g(xx,yy)} >>> "Attempt1.txt"
Where I am solving for two variables and then storing the variables and also a function g(xx,yy) of the variables.
This seems to work for me but the result is not a Matrix any more but the data is stored as some text type thing.
Is there anyway I can get this to stay a matrix or a database where I keep adding rows to it each time I solve for FindRoot by hand? Again, I need to do FindRoot by hand because it is sensitive to the start points and I don't know the good start points without first plotting it.
Thanks a lot
Unless I'm not understanding what you're trying to do, this should work
results = {};
results = Append[Flatten[{{xx, yy} = {x, y} /. FindRoot[{f1(x,y) == 0,f2(x,y)==0}, {x,a},{y,b}],g(xx,yy)}],results];
Then every time you're tying to add a line to the matrix results by hand, you would just type
results = Append[Flatten[{{xx, yy} = {x, y} /. FindRoot[{f1(x,y) == 0,f2(x,y)==0}, {x,a},{y,b}],g(xx,yy)}],results];
By the way, to get around the problem of sensitivity to the initial a and b values, you could explore the parameter space in a loop, varying the parameters slowly and using the solution of x and y from the previous loop iteration for your new a and b values each time.
What you want to do can be achieved by using Read instead of Get. While Get reads the complete file in one run, Read can be adjusted to extract a single Expression, Byte, Number and many more. So what you should do is open your file and read expression after expression and pack it inside a list.
PutAppend[{{1, 2}, {3, 4}}, "tmp.mx"]
PutAppend[{{5, 6}, {7, 8}}, "tmp.mx"]
PutAppend[{{9, 23}, {11, 12}}, "tmp.mx"]
PutAppend[{{13, 14}, {15, 16}}, "tmp.mx"]
stream = OpenRead["tmp.mx"];
mat = ArrayPad[
NestWhileList[Read[stream, Expression] &,
stream = OpenRead["tmp.mx"], # =!= EndOfFile &], -1];
Close[stream];
And now you have in mat a list containing all lines. The ArrayPad, which cuts off one element at each end is necessary because the first element contains the output of the OpenRead and the last element contains EndOfFile. If you are not familiar with functional constructs like NestWhileList then you can put it in a loop as you like, since it is really just the iterated calls to Read
stream = OpenRead["tmp.mx"];
mat = {};
AppendTo[mat, Read[stream, Expression]];
AppendTo[mat, Read[stream, Expression]];
AppendTo[mat, Read[stream, Expression]];
AppendTo[mat, Read[stream, Expression]];
Close[stream];