How to save and pass a variable in Matlab - matlab

I can find / identify all digits in a number using a recursive function.
My issue is trying to sum the number through each recursion.
I had to initialize sum = 0 at the top of my function statement, and when I return through recursion, I'm always resetting sum back to zero. I do not know how to save a variable without first initalizing it.
Code is below;
function output= digit_sum(input)
sum=0
if input < 10
output = input
else
y=rem(input,10);
sum=sum+y
z=floor(input/10);
digit_sum(z)
end
output=sum
end

Related

Create an array that grows at a regular interval on Matlab

I have been thinking about how to create an array that grows at a regular interval of time (for instance every 5 seconds) on Matlab.
I figured out 2 ways, either using tic/ toc or timer function. Later this program will be complexified. I am not sure which way is the best but so far I am trying with using timer.
Here is what I have tried :
clc;
period=5;%period at which the file should be updated
freq=4;
l=freq*period;
time=[0];
a = timer('ExecutionMode','fixedRate','Period',period,'TimerFcn',{#time_append, time,l,freq},'TasksToExecute',3 );
start(a);
function [time]=time_append(obj,event,time,l,freq)
time_append=zeros(l,1);
last_time=time(end)
for i=1:1:l
time_append(i)=last_time+i/freq;
end
time=[time;time_append];
end
After compiling this code, I only get a time array of length 1 containing the value 0 wheras it should contain values from 0 to 3x5 =15 I think it is a stupid mistake but I can't see why. I have tried the debug mode and it seems that at the end of the line time=[time;time_append], the concatenation works but the time array is reinitialised when we go out of the function. Also I have read that callback function can't have output. Does someone would know how I could proceed? Using globals? Any other suggestion?
Thank you for reading
You can do this by using nested functions. Nested functions allow you to access "uplevel variables", and you can modify those. Here's one way to do it:
function [a, fcn] = buildTimer()
period=5;%period at which the file should be updated
freq=4;
l=freq*period;
time=0;
function time_append(~,~,l,freq)
time_append=zeros(l,1);
last_time=time(end);
for i=1:1:l
time_append(i)=last_time+i/freq;
end
time=[time;time_append];
end
function out = time_get()
out = time;
end
fcn = #time_get;
a = timer('ExecutionMode','fixedRate',...
'Period',period,...
'TimerFcn',{#time_append,l,freq},...
'TasksToExecute',3 );
start(a);
end
Note that the variable time is shared by time_append and time_get. The timer object invokes time_append, and updates time. You need to hand out the function handle time_get to retrieve the current value of time.
>> [a,fcn] = buildTimer; size(fcn()), pause(10); size(fcn())
ans =
21 1
ans =
61 1

use structure in matlab

I want to use structure in matlab but in first iteration it's run correctly and in other iteration give that message .
1x2 struct array with fields:
my code is :
for i=1:lenfd
currow=rees(i,:)
maxcn=max(currow)
if maxcn~=0
maxin=find(currow==maxcn)
ress(i).x =maxin
end
end
thank you.
That message is not a warning or error. That's just MATLAB printing the output of an operation. And it does that by default, unless you suppress it by appending a semicolon to the command:
for ii = 1:lenfd
currow = rees(ii,:); % <=== NOTE: semicolons at the end
maxcn = max(currow);
if maxcn ~= 0
ress(ii).x = find(currow==maxcn);
end
end
Note that max() may have 2 outputs, the second output being the first index into the array where the maximum occurred. If you know beforehand that any maximum will occur only once, you can skip the call to find() and use the second output of max().

function passed as parameter does not evaluate more than once matlab

I am writing a Matlab script which requires the repeated generation of random numbers. I am running into an issue where if I pass my random generation function as a parameter to another function, then within the function to which it is passed, it only evaluates once.
Here is some example code:
This is my file randgen.m:
function number = randgen()
'HELLO WORLD'
number = rand(1);
end
Here is my file problemtester.m:
function arr = problemtester(rgen)
firstrand = rgen();
for i = 1:1000
arr(i) = rgen();
end
When I run the command
x = problemtester(randgen);
HELLO WORLD is printed once, and x is filled with 1000 copies of the same random number, so the function must only have evaluated once even though the loop ran 1000 times. Why is this function only evaluating once, despite the repeated calls to it, and more importantly, how do I make it call on each loop iteration?
By calling the function with
x = problemtester(randgen)
MATLAB will first evaluate randgen, as this is a function (and is callable without any parameters). At that time, HELLO WORLD is printed. The return value of that function call is then passed to problemtester, which saves this one value 1000 times into arr and returns that.
To make problemtester call the function randgen, you have to supply a function handle, which is MATLAB's equivalent to function pointers.
x = problemtester(#randgen)
This prints HELLO WORLD a thousand times, and returns a nice random vector.

Nested if statement in for loop

So heres my script
function printPower
sum=0;
filename=input('Enter a filename: ','s');
power=load(filename);
for i=1:length(power);
if power(i)>=0;
sum=sum+power(i);
end
TP=sum/24;
end
fprintf('Total power: %.1f kWh.\n', TP);
There are negative values in the text file im loading and I want it to only sum the positive ones but it still sums all values.
You could just replace your loop with something like
total = sum(power(power>=0))/24
Personally I think that using the name of a Matlab intrinsic function, such as sum, as a variable name is just asking for trouble though I'm not sure it's caused a problem in your case. That's why the lhs of my statement is the variable total.

How to make a loop which display the output for my program automatically

In my program , suppose I fix no. of users N=6 .
Threshold value of SIR SIRo=6; Output generated is SIRmean=10 (suppose).
I want to make a loop so that
if SIRmean < SIRo
disp N=6
else
decrease the counter till SIRmean> SIRo
and display the value of N for which this condition holds true.
end
You can use simple for loop with downcounter and break on condition:
N=6;
for k=N:-1:0
SIRmean = calc_SIR_mean(N);
if SIRmean < SIRo
disp(['N=' k])
break;
end
end
Function calc_SIR_mean should return mean value based on number of users (it is not clear from your question how you receive this value).