Function not processing dat for each element in array
Show older comments
Hi
I need to preform a simple temperture compensation.
I have variable called iot_temperture, which returns the temperture for 10K data points.
I then have a function
function per = tempcorrect(n)
%disp(n)
if n >= 50
per = 115;
elseif n >=40
per = 108;
elseif n >=30
per = 145;
elseif n >=20
per = 120;
% elseif temp >=10
% per = 95;
% elseif temp >=0
% per = 87;
% elseif temp >=-10
% per = 85;
% elseif temp >=-20
% per = 90;
% elseif temp >=-30
% per = 105;
else
per = 100;
end
% x=[-30,-20,-10,0,10,20,30,40,50]
% 105 90 85 87 95 100 105 108 115
end
The function aims to return the the correction factor for a perticular
Therefore when i run the following code, i am expecting correction factor for all 10K points, but all i get is 100 ouput.
a=tempcorrect(iot_temperture)
What am i doing wrong?
Accepted Answer
More Answers (1)
Remember, that Matlab's IF condition must be a scalar. If you provide n as a vector, the line:
if n >= 50
implicitly performs:
if all(n >= 50) && ~isempty(n)
You either need a loop over the elements of n or logical indexing:
per = zeros(size(n));
for k = 1:numel(n)
if n(k) >= 50
per(k) = 115;
...
or
per = repmat(100, size(n));
per(n >= 20) = 120; % From small to large values
per(n >= 30) = 145;
or
Edge = [-inf, 20, 30, 40, 50, inf];
Value = [100, 120, 145, 108, 115];
Group = discretize(n, Edge);
per = Value(Group)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!