how to control return variable in matlab - matlab

i want to clarify how to control returning of variables from function in matlab,for exmaple let us consider this code
function [x y z]=percentage(a)
n=length(a);
maximum=0;
minimum=0;
subst=0;
minus=0;
plus=0;
minus_perc=0;
plus_perc=0;
for i=1:1:n
if a(i)>0
plus=plus+1;
else
minus=minus+1;
end
end
minuc_perc=minus/n;
plus_perc=plus/n;
maximum=max(minus_perc,plus_perc);
minimum=min(minus_perc,plus_perc);
subst=maximum-minimum;
x=plus_perc;
y=minus_perc;
z=subst*100;
if plus_perc>minus_perc
disp('among the successful people,relevant propession was choosen by');
disp(z)
disp('% people');
else
disp('among the successful people,irrelevant propession was choosen by');
disp(z);
disp('% people');
end
end
what i want to return is plus_proc,min_proc and subst,but when i run following command,get result like this
[c d e]=percentage(a)
among the successful people,relevant propession was choosen by
58.3333
% people
c =
0.5833
d =
0
e =
58.3333
so i think something is wrong,array is like this
a =
1 -1 1 1 -1 1 -1 -1 1 1 1 -1
so ones again,i want to return plus_proc,minus_proc,and subst

To return a variable in matlab you just assign into one of the specified return parameters. For example: to return the number five I would use:
function [foo] = gimmeFive()
foo = 5;
end
Your code is not giving you the right answer because you have a typo:
minuc_perc=minus/n;
should be
minus_perc=minus/n;
You could greatly simplify the function by taking advantage of the find function, like so:
Find the indeces of any element of a > 0, count them.
plus = length(find(a > 0));
plus_perc = plus ./ length(a);
Or if you want to cut even more out:
a > 0 gives us a vector of 0 and 1, so sum up the 1's
plus = sum(a > 0);
plus_perc = plus ./ length(a);

Related

Numeric Data Validation While Loop in Matlab

I have a function usenum
function TF = usenum(x)
TF = false;
if ~isnumeric(x)
h = msgbox('Input is not numeric');
elseif (x <= 0)
h = msgbox('Input must be > 0');
else
TF = true;
end
I am getting user input in the main menu:
answer = inputdlg(prompt,dlg_title,num_lines,def);
The inputdlg has 2 values and can be indexed by {1} and {2}
I want to wait for the user to input a value, the value has to be a number and greater than 0. in the case that he doesn't, I want to output the respective message and make him keep inputting until he gets it right, or close the inputdlg dialog.
I am attempting something like this:
condition = false;
while ~condition
answer = inputdlg(prompt,dlg_title,num_lines,def);
numOfTracks = answer{1};
bpmRange = answer{2};
condition = usenum(numOfTracks);
end
I am trying to say, while condition = false, i.e. while input is not numeric or not greater than 0, keep getting user input. Once the user inputs a valid number the condition is supposed to become true and the while is supposed to terminate. However, the inputdlg keeps opening for input and the only way I can stop it is by closing it (infinite loop). how can I achieve what I want?
Thanks in advance
Your loop appears to be correct. The following testing provides results of your usenum function.
>> usenum('')
ans =
0
>> usenum(-1)
ans =
0
>> usenum(1)
ans =
1
Your usenum function is correct as far as typing is concerned, but I believe your input is always given as a string since you're getting user input from a dialogue. Instead, you should try redefine usenum as follows if you're expecting a string input. The function str2double converts it to a double and if it's text, it will show as NaN. That's what the isnan check is for, to check if it's text.
function TF = usenum(x)
% Default to false
TF = false;
x = str2double(x);
% Check if digits
if isnan( x )
h = msgbox('Input is not numeric');
elseif (x <= 0)
h = msgbox('Input must be > 0');
else
TF = true;
end
This is the result of the new function.
>> usenum('a')
ans =
0
>> usenum('-1')
ans =
0
>> usenum('1')
ans =
1

How to disable outputting variables inside Octave function

I wrote my own function for Octave, but unfortunately aside of the final result value, the variable "result" is written to console on every change, which is an unwanted behavior.
>> a1 = [160 60]
a1 =
160 60
>> entr = my_entropy({a1}, false)
result = 0.84535
entr = 0.84535
Should be
>> a1 = [160 60]
a1 =
160 60
>> entr = my_entropy({a1}, false)
entr = 0.84535
I don't get the idea of ~ and it don't work, at least when I tried.
Code is as follows:
# The main difference between MATLAB bundled entropy function
# and this custom function is that they use a transformation to uint8
# and the bundled entropy() function is used mostly for signal processing
# while I simply use a straightforward solution usefull e.g. for learning trees
function f = my_entropy(data, weighted)
# function accepts only cell arrays;
# weighted tells whether return one weighed average entropy
# or return a vector of entropies per bucket
# moreover, I find vectors as the only representation of "buckets"
# in other words, vector = bucket (leaf of decision tree)
if nargin < 2
weighted = true;
end;
rows = #(x) size(x,1);
cols = #(x) size(x,2);
if weighted
result = 0;
else
result = [];
end;
for r = 1:rows(data)
for c = 1:cols(data) # in most cases this will be 1:1
omega = sum(data{r,c});
epsilon = 0;
for b = 1:cols(data{r,c})
epsilon = epsilon + ( (data{r,c}(b) / omega) * (log2(data{r,c}(b) / omega)) );
end;
if (-epsilon == 0) entropy = 0; else entropy = -epsilon; end;
if weighted
result = result + entropy
else
result = [result entropy]
end;
end;
end;
f = result;
end;
# test cases
cell1 = { [16];[16];[2 2 2 2 2 2 2 2];[12];[16] }
cell2 = { [16],[12];[16],[2];[2 2 2 2 2 2 2 2],[8 8];[12],[8 8];[16],[8 8] }
cell3 = { [16],[3 3];[16],[2];[2 2 2 2 2 2 2 2],[2 2];[12],[2];[16],[2] }
# end
In your code, you should end lines 39 and 41 with semicolon ;.
Lines finishing in semicolon aren't shown in stdout.
Add ; after result = result + entropy and result = [result entropy] in your code, or in general after any assignment that you don't want printed on screen.
If for some reason you can't modify the function, you can use evalc to prevent unwanted output (at least in Matlab). Note that the output in this case is obtained in char form:
T = evalc(expression) is the same as eval(expression) except that anything that would normally be written to the command window, except for error messages, is captured and returned in the character array T (lines in T are separated by \n characters).
As with any eval variant, this approach should be avoided if possible:
entr = evalc('my_entropy({a1}, false)');

Identifying a flag set and printing a message in Matlab

Hi all I am working on checking for certain cases in a large loop, with in this large loop is this statement:
%Center Dialouge
timers_c = [start_dpc_sh_hi_timer_c, start_dpc_sh_lo_timer_c, start_ffm_sh_act_hi_timer_c,...
start_ffm_sh_act_lo_timer_c, start_hpot_eff_loss_timer_c, start_lfpt_dpsh_timer_c,...
start_pc_sh_time_c, start_post_tl_nl_c, start_pre_tl_nl_c, start_elec_lu_timer_c];
if perf_case_c ~= -1
for k = 1:10
if iscellstr(timers_c(k)) == 1
perf_case_timer_c = timers_c{k};
timer_set_c = 1;
end
end
end
To I identify the start time and the case type to be output in a dialogue message:
if timer_set_c == 1
pcase_c = msgbox([sprintf('%s'),perf_case_c,sprintf('\nMET:%s\n'),perf_case_timer_c],'PERFORMANCE CASE');
end
I can't get the if statement that determines which case has been determined to work. I am trying to use the change from -1 to a string somehow, but it doesn't quite work.
A minimal example would be
%Assume all timers initialized as zero
%Assume case ~= -1 (is a char array, string
timers_c = [timer1, timer2, timer3 ]
if case ~= -1
for k = 1:3
if iscellstr(timer_c(k)) ==1
case_time = timers(c{k});
time_set_flag = 1
end
end
end
...
and then outside of the loop would be the above msgbox

How to improve execution time of the following Matlab code

Please help me to improve the following Matlab code to improve execution time.
Actually I want to make a random matrix (size [8,12,10]), and on every row, only have integer values between 1 and 12. I want the random matrix to have the sum of elements which has value (1,2,3,4) per column to equal 2.
The following code will make things more clear, but it is very slow.
Can anyone give me a suggestion??
clc
clear all
jum_kel=8
jum_bag=12
uk_pop=10
for ii=1:uk_pop;
for a=1:jum_kel
krom(a,:,ii)=randperm(jum_bag); %batasan tidak boleh satu kelompok melakukan lebih dari satu aktivitas dalam satu waktu
end
end
for ii=1:uk_pop;
gab1(:,:,ii) = sum(krom(:,:,ii)==1)
gab2(:,:,ii) = sum(krom(:,:,ii)==2)
gab3(:,:,ii) = sum(krom(:,:,ii)==3)
gab4(:,:,ii) = sum(krom(:,:,ii)==4)
end
for jj=1:uk_pop;
gabh1(:,:,jj)=numel(find(gab1(:,:,jj)~=2& gab1(:,:,jj)~=0))
gabh2(:,:,jj)=numel(find(gab2(:,:,jj)~=2& gab2(:,:,jj)~=0))
gabh3(:,:,jj)=numel(find(gab3(:,:,jj)~=2& gab3(:,:,jj)~=0))
gabh4(:,:,jj)=numel(find(gab4(:,:,jj)~=2& gab4(:,:,jj)~=0))
end
for ii=1:uk_pop;
tot(:,:,ii)=gabh1(:,:,ii)+gabh2(:,:,ii)+gabh3(:,:,ii)+gabh4(:,:,ii)
end
for ii=1:uk_pop;
while tot(:,:,ii)~=0;
for a=1:jum_kel
krom(a,:,ii)=randperm(jum_bag); %batasan tidak boleh satu kelompok melakukan lebih dari satu aktivitas dalam satu waktu
end
gabb1 = sum(krom(:,:,ii)==1)
gabb2 = sum(krom(:,:,ii)==2)
gabb3 = sum(krom(:,:,ii)==3)
gabb4 = sum(krom(:,:,ii)==4)
gabbh1=numel(find(gabb1~=2& gabb1~=0));
gabbh2=numel(find(gabb2~=2& gabb2~=0));
gabbh3=numel(find(gabb3~=2& gabb3~=0));
gabbh4=numel(find(gabb4~=2& gabb4~=0));
tot(:,:,ii)=gabbh1+gabbh2+gabbh3+gabbh4;
end
end
Some general suggestions:
Name variables in English. Give a short explanation if it is not immediately clear,
what they are indented for. What is jum_bag for example? For me uk_pop is music style.
Write comments in English, even if you develop source code only for yourself.
If you ever have to share your code with a foreigner, you will spend a lot of time
explaining or re-translating. I would like to know for example, what
%batasan tidak boleh means. Probably, you describe here that this is only a quick
hack but that someone should really check this again, before going into production.
Specific to your code:
Its really easy to confuse gab1 with gabh1 or gabb1.
For me, krom is too similar to the built-in function kron. In fact, I first
thought that you are computing lots of tensor products.
gab1 .. gab4 are probably best combined into an array or into a cell, e.g. you
could use
gab = cell(1, 4);
for ii = ...
gab{1}(:,:,ii) = sum(krom(:,:,ii)==1);
gab{2}(:,:,ii) = sum(krom(:,:,ii)==2);
gab{3}(:,:,ii) = sum(krom(:,:,ii)==3);
gab{4}(:,:,ii) = sum(krom(:,:,ii)==4);
end
The advantage is that you can re-write the comparsisons with another loop.
It also helps when computing gabh1, gabb1 and tot later on.
If you further introduce a variable like highestNumberToCompare, you only have to
make one change, when you certainly find out that its important to check, if the
elements are equal to 5 and 6, too.
Add a semicolon at the end of every command. Having too much output is annoying and
also slow.
The numel(find(gabb1 ~= 2 & gabb1 ~= 0)) is better expressed as
sum(gabb1(:) ~= 2 & gabb1(:) ~= 0). A find is not needed because you do not care
about the indices but only about the number of indices, which is equal to the number
of true's.
And of course: This code
for ii=1:uk_pop
gab1(:,:,ii) = sum(krom(:,:,ii)==1)
end
is really, really slow. In every iteration, you increase the size of the gab1
array, which means that you have to i) allocate more memory, ii) copy the old matrix
and iii) write the new row. This is much faster, if you set the size of the
gab1 array in front of the loop:
gab1 = zeros(... final size ...);
for ii=1:uk_pop
gab1(:,:,ii) = sum(krom(:,:,ii)==1)
end
Probably, you should also re-think the size and shape of gab1. I don't think, you
need a 3D array here, because sum() already reduces one dimension (if krom is
3D the output of sum() is at most 2D).
Probably, you can skip the loop at all and use a simple sum(krom==1, 3) instead.
However, in every case you should be really aware of the size and shape of your
results.
Edit inspired by Rody Oldenhuis:
As Rody pointed out, the 'problem' with your code is that its highly unlikely (though
not impossible) that you create a matrix which fulfills your constraints by assigning
the numbers randomly. The code below creates a matrix temp with the following characteristics:
The numbers 1 .. maxNumber appear either twice per column or not at all.
All rows are a random permutation of the numbers 1 .. B, where B is equal to
the length of a row (i.e. the number of columns).
Finally, the temp matrix is used to fill a 3D array called result. I hope, you can adapt it to your needs.
clear all;
A = 8; B = 12; C = 10;
% The numbers [1 .. maxNumber] have to appear exactly twice in a
% column or not at all.
maxNumber = 4;
result = zeros(A, B, C);
for ii = 1 : C
temp = zeros(A, B);
for number = 1 : maxNumber
forbiddenRows = zeros(1, A);
forbiddenColumns = zeros(1, A/2);
for count = 1 : A/2
illegalIndices = true;
while illegalIndices
illegalIndices = false;
% Draw a column which has not been used for this number.
randomColumn = randi(B);
while any(ismember(forbiddenColumns, randomColumn))
randomColumn = randi(B);
end
% Draw two rows which have not been used for this number.
randomRows = randi(A, 1, 2);
while randomRows(1) == randomRows(2) ...
|| any(ismember(forbiddenRows, randomRows))
randomRows = randi(A, 1, 2);
end
% Make sure not to overwrite previous non-zeros.
if any(temp(randomRows, randomColumn))
illegalIndices = true;
continue;
end
end
% Mark the rows and column as forbidden for this number.
forbiddenColumns(count) = randomColumn;
forbiddenRows((count - 1) * 2 + (1:2)) = randomRows;
temp(randomRows, randomColumn) = number;
end
end
% Now every row contains the numbers [1 .. maxNumber] by
% construction. Fill the zeros with a permutation of the
% interval [maxNumber + 1 .. B].
for count = 1 : A
mask = temp(count, :) == 0;
temp(count, mask) = maxNumber + randperm(B - maxNumber);
end
% Store this page.
result(:,:,ii) = temp;
end
OK, the code below will improve the timing significantly. It's not perfect yet, it can all be optimized a lot further.
But, before I do so: I think what you want is fundamentally impossible.
So you want
all rows contain the numbers 1 through 12, in a random permutation
any value between 1 and 4 must be present either twice or not at all in any column
I have a hunch this is impossible (that's why your code never completes), but let me think about this a bit more.
Anyway, my 5-minute-and-obvious-improvements-only-version:
clc
clear all
jum_kel = 8;
jum_bag = 12;
uk_pop = 10;
A = jum_kel; % renamed to make language independent
B = jum_bag; % and a lot shorter for readability
C = uk_pop;
krom = zeros(A, B, C);
for ii = 1:C;
for a = 1:A
krom(a,:,ii) = randperm(B);
end
end
gab1 = sum(krom == 1);
gab2 = sum(krom == 2);
gab3 = sum(krom == 3);
gab4 = sum(krom == 4);
gabh1 = sum( gab1 ~= 2 & gab1 ~= 0 );
gabh2 = sum( gab2 ~= 2 & gab2 ~= 0 );
gabh3 = sum( gab3 ~= 2 & gab3 ~= 0 );
gabh4 = sum( gab4 ~= 2 & gab4 ~= 0 );
tot = gabh1+gabh2+gabh3+gabh4;
for ii = 1:C
ii
while tot(:,:,ii) ~= 0
for a = 1:A
krom(a,:,ii) = randperm(B);
end
gabb1 = sum(krom(:,:,ii) == 1);
gabb2 = sum(krom(:,:,ii) == 2);
gabb3 = sum(krom(:,:,ii) == 3);
gabb4 = sum(krom(:,:,ii) == 4);
gabbh1 = sum(gabb1 ~= 2 & gabb1 ~= 0)
gabbh2 = sum(gabb2 ~= 2 & gabb2 ~= 0);
gabbh3 = sum(gabb3 ~= 2 & gabb3 ~= 0);
gabbh4 = sum(gabb4 ~= 2 & gabb4 ~= 0);
tot(:,:,ii) = gabbh1+gabbh2+gabbh3+gabbh4;
end
end

Indexing arrays in matlab from 0

For the math class I'm taking, I have to write a program to compute the FFT of a function. We have been given the code in class. I'm having problems entering the code in matlab because the index starts at 0. This is the code given in class:
Input: q,N,f(k)
Output: d(k)
sigma(0) = 0
for r = 0 to q-1
for k = 0 to (2^r)-1
sigma((2^r)+k) = sigma(k) + 2^(q-1-k)
end
end
for k = 0 to N-1
d(k) = f(sigma(k))/N
end
for r = 0 to q-1
M = 2^r
Theta = e^(-i*pi()/M)
for k = 0 to M-1
for j = 0 to 2^(q-1-r)-1
x = theta^(k)*d(2*j*M+k)-x
d(2*j*m+k) = d(2*j*M+k)+x
end
end
end
Normally this would not be hard to implement but, the indicies are throwing me off. How do I write this code starting the loops at index 1 instead of 0(the program has to be written in Matlab)? Normally I would just manually calculate the first term(0 term) and put it outside the loop and then, shift the loop by one index. This problem however is not that simple. Thanks.
Just add one whenever you're indexing into an array. For example:
sigma((2^r)+k+1) = sigma(k+1) + 2^(q-1-k)
Also, use 1i when you mean sqrt(-1) since it's clearer, safer, since you can overwrite the meaning of i or j accidentally, and faster.
i would do every array index as "i array index" and then immediately change array index to be i array index - 1. you can then use array index for the mathematical portion and i*array index* to index specified arrays.
example:
instead of
for i = 0:n
sum = sum + i*array(i);
end
i would do
for ii = 1:n+1
i = ii-1;
sum = sum + i*array(ii);
end
EDIT: incredibly stupid typo: ii should go from 1:n+1 - that was the entire point of my change!