Problems Detail:
My routine is a simple set of equations, the result must yield the result as an array of float elements with a precission of 4 decimals. The problem is that the .round(4) method is not working.
What I tried:
Used .round(4)
Used .to_f(4)
My code is as follows:
`
def bar_triang(p1,p2,p3)
#your code here
bary=[]
x0= [p1[0],p2[0],p3[0]].sum
x0t= x0.div(3)
x0tf = x0t.round(4)
bary=bary.push(x0tf)
y0 = [p1[1],p2[1],p3[1]].sum
y0t =y0.div(3)
y0tf = y0t.round(4)
bary=bary.push(y0tf)
p bary
end
`
Note: The routine accepts an array of the following shape [p1,p2,p3] in which p1 to p3 are coordinates [x,y]. [p1,p2,p3] is an array of arrays.
What I am expecting?
An array of two float elements with 4 decimals of precission.
What I am getting?
An array of two float elements with no decimals precission.
What I want to know?
Why the .round(4) method does not work in the context of my code?
How can I use .round(4) within the context of my code in order to make it work properly?
Your problem is not because the round(4) not working correctly. It's because part of code:
x0t = x0.div(3) # Always return Integer
x0tf = x0t.round(4)
I suggest using / instead of div:
x0t = x0 / 3 # return Float
x0tf = x0t.round(4)
Related
I have made this function rounds() which rounds the values to the nearest multiple of 0.5, ie, rounds(2.685)=2.5 rounds(2.332)=2.5 rounds(2.7554)=3.0 rounds(2.245)=2.0 it works well in the way mentioned above, but while handling large number of values the precision drop. It does not give me the desired results. I have 30 functions, each of them computes 14 values which I pass in rounds() as a whole vector containing those 14 values. The results are like, for values for which it should return 3.0 such as rounds(2.7554) it only returns 2.5 and that affects my overall accuracy alot. Individually it works well for all values even 2.7554 returns 3.0 when i pass it to check its working. Can anyone tell me why this happens that while handling large number of values its performance decreases and also tell me the solution.
function [newVal] = rounds(x)
dist = mod(x, 0.5);
floorVal = x - dist;
if dist >=0.25
newVal = floorVal + 0.5;
else
newVal = floorVal;
end
end
The above is the rounds function and below i am showing how i have used it my functions.
if true
calc(1) = x+y;
calc(2) = x-y;
calc(3) = x*y+a;
.......
.......
.......
calc(14) = a+b*c+x;
calc = calc';
final_calc = rounds(calc);
end
Even in a single function the rounds function handles only 14 values at once still the result is not precised, while if i pass those same values individually it gives the correct output. Please solve this issue someone. Thanks in advance.
function [newVal] = rounds2(x)
newVal = round(x/0.5)*0.5;
end
This was something i was struggling for a long time but here I have now a perfect answer. This was happening because i was passing the vector expression dist >= 0.25 to if...end, incorrectly thinking that the if...end will be evaluated separately for each element of x(i). Hope that it helps some others too
I am trying to return a 4D array of image data from a function call in MATLAB. I'm not very advanced in MATLAB and I don't know what type of data I have to return from the function. Here is my function:
function classimg = loadImages(classdir,ext)
% create array of all images in directory
neg = dir([classdir ext]);
% get size of array (to loop through images)
numFileNeg = max(size(neg));
% create a 4D array to store our images
classimg = zeros(51,51,3,numFileNeg);
% loop through directory
for i=1:numFileNeg
classimg(:,:,:,i) = imread([myDir neg(i).name]);
end
end
Here is the function call:
negativeImgs = loadImages("C:\Users\example\Documents\TrainingImages\negatives\","*.jpg");
I cannot find any online documentation for the return type? Does anyone know what this would be? classimg is populated correctly so the code inner works.
You initialize classimg to be a 51x51x3xnumFileNeg matrix of zeros. You use the zeros function, so the datatype is double. To see this clearly, call your function from the command window, and then type "whos" to see both the size and datatype of classimg.
As Mike correctly points out, since you initialize classimg using zeros, and the default data type is double, your image data will be converted to double from whatever data type imread returns (often uint8).
If you would like classimg to be the same data type as your images (which I'm assuming all have the same type), you can load one image, get its class, and initialize classimg with that specific class. Here's how you could rewrite your function:
function classimg = loadImages(classdir, ext)
neg = dir(fullfile(classdir, ext));
numFileNeg = numel(neg);
tempImage = imread(fullfile(classdir, neg(1).name));
classimg = zeros(51, 51, 3, numFileNeg, class(tempImage));
classimg(:, :, :, 1) = tempImage;
for i = 2:numFileNeg
classimg(:, :, :, i) = imread(fullfile(classdir, neg(i).name));
end
end
Note that I made a couple of other changes. I used fullfile instead of concatenation of the directory and file names, since it handles any issues with file separators for you. I also used numel to get the number of files as Justin suggested in a comment.
I am making a pyomo model, where i want to use random numbers for my two dimensional parameters. I put a small python script for random numbers that looks exactly what i wanted to see for my two dimensional parameter. I am getting a TypeError: Cannot convert object of type 'list'(value =[[....]] to a numeric value. in my objective function. Below is my objective function and random numbers script.
model.obj = Objective(expr=sum(model.C[v,l] * model.T[v,l] for v in model.V for l in model.L) + \
sum(model.OC[o,l] * model.D[o,l] for o in model.O for l in model.L), sense=minimize)
import random
C = [[] for i in range(7)]
for i in range(7):
for j in range(5):
C[i]+= [random.randint(100,500)]
model.C = Param(model.V, model.L, initialize=C)
Please let me know if someone can help fixing this.
You should initialize your parameter using a function instead of a nested list
def init_c(m, i, j):
return random.randint(100,500)
model.c = Param(model.V, model.L, initialize=init_c)
I have matrix with 400 rows and 40 columns.
I would like to create a new matrix from this data where I calculate the concordance between 2 variables, i.e., concord [A1,B1]=number1; concord [A1,B2]=number2; [A1,B39]=number39. So, number1 should now be the first number of the first row of a new matrix; number 2 is the second number in the first row....
The end result is a new matrix that shows the rho_c for each pair of numbers in the original data matrix.
The original matrix has a lot of empty cells. I can also create multiple matrix of subsections of concordance calculations, it doesn't matter much. However, I don't quite understand how to write this command in mata.
I've searched here: http://jasoneichorst.com/wp-content/uploads/2012/01/BeginMatrix.pdf
EDIT: The data looks like this (variable "Score1" is a rater). Not all raters rate the same item.
enter image description here
Assuming I fully understand the question, there are methods to do this. One which comes to mind involves the use of concord available from SSC (ssc install concord) along with some local macros and loops.
/* Clear and set up sample data */
clear *
set obs 60
forvalues i = 1/6 {
gen A`i' = runiform()
}
replace A2 = . in 10/L
replace A3 = . in 1/5
replace A3 = . in 20/L
replace A4 = . in 1/20
replace A4 = . in 30/L
replace A5 = . in 1/15
replace A5 = . in 40/L
replace A6 = . in 1/40
/* End data set-up */
* describe, varlist will allow you to store your variables in a local macro
qui describe, varlist
local vars `r(varlist)'
* get number of variables in local macro vars
local varcount : word count `vars'
* Create a matrix to hold rho_c
mat rho = J(6,6,.)
mat rownames rho = `vars'
mat colnames rho = `vars'
* Loop through vars to run concord on all unique combinations of A1-A6
* using the position of each variable in local vars to assign the var name
* to local x and local y
* concord is executed only for j >= i so that you don't end up with two sets
* of the same variables being ran (eg., A1,A2 and A2,A1)
forvalues i = 1/`varcount' {
local y `: word `i' of `vars''
forvalues j = 1/`varcount' {
local x `: word `j' of `vars''
if `j' >= `i' {
capture noisily concord `y' `x'
mat rho[`i',`j'] = r(rho_c)
}
}
}
* Display the results stored in the matrix, rho.
mat list rho
The above code should get you started, but there may need to be changes made depending on exactly what you want to do.
You will notice that inside of the loop, I have included capture noisily before concord. The reason for this is because in the image you linked to, your variables were missing values across entire sections of observations. This will likely result in an error message being thrown (specifically, r(2000): no observations). The capture piece forces Stata to continue to execute the loop if an error occurs there. The noisily piece tells Stata to display the output from concord even though capture was specified.
Also, if you search help concord in Stata, you will be directed to the help page which indicates that the concordance correlation coefficient is stored in r(rho_c). You can store these as individual scalars inside the loop or do as in the example and create a kxk matrix of values.
I was new to Matlab,and this time I want to create a function for its image process.
Firstly, I download a picture from the Internet.Then I named it "map.jpg",and copy to my workspace.latter,I create a M_files and type the code into the files.
for example:
function y=mean_data(gray)
s=size(gray);
sum=0;
for i=1:s(1)
for j=1:s(2)
sum=sum+gray(i,j);
end
end
y=sum/(s(1)*s(2));
Finally,the difference happenend:
if I call the function in this way:
I=imread('map.jpg');
J=rgb2gray(I);
mean=mean_data(double(J))
the result will be OK.
However if I call in this way:
I=imread('map.jpg');
J=rgb2gray(I);
mean=mean_data(J)
the result will be zero.
So why does the result being so different?And thank you for helping me!!!
This is becuase the default output format of the data read by imread
is uint8 that is - 8 bit per R/G/B. With 8 bit you can't get any integer
higher than 255. Take a look:
>> uint8(250) + uint8(5)
ans =
255
>> uint8(250) + uint8(6)
ans =
255
So then, during division in your function this thing happens:
>> uint8(255) / 12345
ans =
0
However, when you use double() you change the representation of
your data to 64 bit floating point - a lot more room for representing big
numbers.
Instead of using your loop function you can use matlab's mean
function - it works well with uint8 format:
>> mean(uint8([255, 231]))
ans =
243
So you can use:
mean_dat = mean(mean(J));
% it is also not a good idea to name a variable 'mean'
% if you are going to use the mean function so I renamed
% your variable to mean_dat