I am new in GUI Matlab. I want to have a table of values in GUI, which get results from m.file. The table is of 9x10. (9 parameters, each will get 10 results). In m.file, I have a loop of getting the results of these 9 parameters and this loop iterates 10 time. I want to save the result 9 parameter per iteration of loop in a row of this table. How I can proceed? Thanks in advance.
You can save them into a 9x10 matrix and loop writing parameters into it. Like this:
res = zeros(9, 10);
for i=1:9
for j=1:10
res(i, j) = ...
end
end
Related
total_Route = zeros(4,4);
tmp = evalin('base', 't'); % i initialise t in the Workspace with the value 1
if(tmp==5)
tmp=1;
end
total_Route(tmp,1) = Distance_Traveled_CM;
total_Route(tmp,2) = Hauptantrieb_Verbrauchte_Energie_CM;
total_Route(tmp,3) = Nebenaggregate_Verbrauch_Real_CM;
total_Route(tmp,4) = t;
Total_Distance_Traveled_CM = sum(total_Route(:,1));
set(handles.edit3, 'string',Total_Distance_Traveled_CM);
Total_Hauptantrieb_Verbrauchte_Energie_CM = sum(total_Route(:,2));
set(handles.edit4, 'string',Total_Hauptantrieb_Verbrauchte_Energie_CM);
Total_Nebenaggregate_Verbrauch_Real_CM = sum(total_Route(:,3));
set(handles.edit5, 'string',Total_Nebenaggregate_Verbrauch_Real_CM);
%% Index
set(handles.edit15, 'string',tmp);
assignin('base', 't', tmp + 1); % with this line i can increment "t" after each pass
guidata(hObject,handles);
Sorry that I did not explain my problem well.
#Sardar_Usama I want to run the loop only once but t should be incremented after each time I click on my Button.
# Sembei Norimaki end is at the end of my codes, have forgotten to write it in my question
#Patrik & #Dennis Jaheruddin let me explain my problem again
I created a Matrix with 4×4 Elements with the Goal to save the results of each my Variable (Total_Distance_Traveled_CM, Total_Hauptantrieb_Verbrauchte_Energie_CM etc...) after each Simulation in the element of my Matrix (See image below).
I want by pressing a button (on my GUI) to get always the sum of each Column.
Example
The first pass: t = 1--> Distance_Traveled(1,1) is 900 the GUI will take through clicking on the Button, the sum of the first column (which is 900+0+0+0) and write it in a static test.
The second pass t = 2--> Distance_traveled(2,1) is 800 the GUI will take the sum of the first column (which is 900+800+0+0) and write it in a static test and the same thing should happen with the other column.
This should continue until t = 4 i.e. until it does the same thing for each column, then it should reset.
I hope, I have explained my problem better this time and I apologize for my bad English.
I appreciate any help.
Based on your code fragment the for loop is only called once.
However, the contents of the for loop are ran for four times. (first for i=1 then for 1=2 etc..)
If you only want to run one of these options the solution is very simple:
i = 1
yourLoopContent
If i is always 0 the first time, and you always want to run it for the current i, it would also be simple:
yourLoopContent
i = i+1;
However if i may not be set properly the first time, things get messy. This is because i is by default defined as the square root of minus 1.
Therefore I would recommend you to use a different letter like t instead. Then you could do this:
if ~exists(t)
t=0;
end
yourLoopContent %Everywhere using t instead of i
t = t+1;
In general you may want to avoid i as an index to stay clear of complex number issues.
I'm not sure if I got your question correctly, but it seems to me that what you look for is a cumulative sum. This can be done either buy summing on 1:t or by using cumsum. I'm not sure why you use a loop, but if this is only for the summing then cumsum can replace that.
Here is some example in your code:
total_Route = zeros(4,4);
% I commented below what is not part of the question
for t = 1:4
total_Route(t,:) = [Distance_Traveled_CM,
Hauptantrieb_Verbrauchte_Energie_CM,
Nebenaggregate_Verbrauch_Real_CM,
t];
% the following line compute the comulative sum from the top of each
% column to every element in it, so cs_total_Route(3,2) is like
% sum(total_Route(1:3,2)):
cs_total_Route = cumsum(total_Route);
Total_Distance_Traveled_CM = cs_total_Route(t,1); % OR sum(total_Route(1:t,1))
% set(handles.edit3, 'string',Total_Distance_Traveled_CM);
Total_Hauptantrieb_Verbrauchte_Energie_CM = cs_total_Route(t,2); % OR sum(total_Route(1:t,2))
% set(handles.edit4, 'string',Total_Hauptantrieb_Verbrauchte_Energie_CM);
Total_Nebenaggregate_Verbrauch_Real_CM = cs_total_Route(t,3); % OR sum(total_Route(1:t,3))
% set(handles.edit5, 'string',Total_Nebenaggregate_Verbrauch_Real_CM);
% set(handles.edit15, 'string',t);
end
And here is a quick look on what cumsum does (with some random numbers for total_Route):
total_Route =
671 4.6012 1.0662 1
840 3.6475 0.58918 2
354 8.6056 2.1313 3
893 4.1362 2.0118 4
cs_total_Route =
671 4.6012 1.0662 1
1511 8.2487 1.6554 3
1865 16.854 3.7867 6
2758 20.991 5.7985 10
Is this what you looked for?
This is a simplified version of my code. What i want to obtain is a variable1 - row vector contained in result.mat. Problem is that parsave - saves only one result, the last one from the 10th iteration. What can i do to save all results in one vector (in variable1) inside the parfor loop?
parfor ii = 1:10
[variable1, variable2] = MyFunction(~,~,ii);
parsave('result.mat',variable1, variable2)
end
function parsave(filename, varargin)
narginchk(2, Inf);
nargoutchk(0, 0);
for I = 2:nargin
varname = genvarname(inputname(I));
eval([varname ' = varargin{' num2str(I-1) '};'])
if (I == 2)
save(filename, varname)
else
save(filename, varname, '-append')
end
end
Inside parsave, you have the following statement:
if (I == 2)
save(filename, varname)
else
save(filename, varname, '-append')
end
Thus, on your first pass of parsave, every time you run parsave, you overwrite filename.
In addition, your code is a huge risk for a race-condition: Assume two processes try to do the "initial save" of the file at the same time - one is going to overwrite the other, or throws a "cannot access file" error.
You're much better off saving to temp files in the parfor loop, and to follow this up with an aggregator function that combines the different saves into something useful - or simply save into a new directory every time you run the loop, rather than creating a new file.
Got an elegant solution on http://www.mathworks.com/matlabcentral/answers/179884-save-inside-parfor-loop-at-a-specific-iteration-step
parpool('local',10); % results will be distributed on 10 workers
output1=distributed.NaN(1,1e5); %pre-allocate
output2=distributed.NaN(1,1e5);
spmd
for i=drange(1:1e5)
[output1(ii), output2(ii)] = MyFunction(~,~,ii);
parsave(['output1', num2str(labindex)],...
getLocalPart(output1));
parsave(['output2', num2str(labindex)],...
getLocalPart(output2));
end
end
I've used 2 times the parsave function so in case that the machine shuts down before the simulation ends, 10 mat files will be saved with temporary results that I'll need to concatenate later (for output1 & output2)
The parsave function is:
function parsave(fname,data)
var_name=genvarname(inputname(2));
eval([var_name '=data'])
try
save(fname,var_name,'-append')
catch
save(fname,var_name)
end
% Written by Minjie Xu (<mailto:chokkyvista06#gmail.com chokkyvista06#gmail.com>)
I have a problem with kmean. I would like to plot the value of the CostFunction ("sum" in the output shown below) vs. Iteration ("iter") obtained with the kmean algorithm. By altering the input options you can obtain this:
14 iterations, total sum of distances = 731.224
iter phase num sum
1 1 604 847.577
2 1 56 818.135
....
Using this data I want to draw something like this.
Since the iteration-by-iteration progress is apparently not being stored in some object which you can query you have to collect the info being displayed at the command line. One way to do this is as follows:
diary temp
% ....
% execute kmeans here, something like this:
% km = kmeans(H',nbin,'Display','iter');
% ....
diary off
% now extract the line by line result from the diary file called "temp"
fid=fopen('temp');
dat=textscan(fid,'%s');
fclose(fid);
delete temp
dat=dat{1};
i1=find(~cellfun('isempty',strfind(dat,'sum')));
ie=find(~cellfun('isempty',strfind(dat,'iterations')));
i1=i1(1)+1;
Nd=str2num(dat{ie(1)-1});
ie=Nd*4+i1-1;
dat=reshape(str2num(strvcat(dat{i1:ie})),4,Nd)';
iter = dat(:,1) % <-- iterations
sm = dat(:,4) % <-- sum
There may be some way to streamline reading the diary file but this worked for me.
Edit
Before attempting to run a function it's always wise to look over the documentation:
doc kmeans
If iter and sum are stored as variables, you may simply call
plot( iter , sum , 'r' , 'LineWidth' , 1.5 )
or, simplier
plot(sum)
EDIT
I am not familiar with the function, but for saving as workspace variables I would do as follows:
[IDX,C,sumd,D] = kmeans(X,k)
and then just stay with what I mentioned above.
I have
load t1.txt;
load t2.txt;
load t3.txt;
load t4.txt;
data=t1;
vector =[ 2 , 3 , 4 , 5 , 6 ];
for i = vector
[TempFlag, MemberInd] = ismember( i, vector );
fprintf('vector(%d) is %d\n', MemberInd, i);
scatter( data(:,1),data(:,2))
end
if I want to do the above loop with all 4 files, How would you load them in a vector or something, so with each iteration it does other data?.
So I want to avoid:
data = t2;
(loop)
data = t3;
(loop)
etc...
You've set data=1, yet used it like a matrix in this line :scatter( data(:,1),data(:,2))... that should've given you a Index exceeds matrix dimensions error.
Assuming that was a typo, and that you just want to do it for different values of data, use nested loops.
data=[1,2,3,4];
vector=[2,3,4,5,6];
for i=data
for j=vector
<do stuff here>
end
end
EDIT
If your files are named t-{a,e,i,o,u} and the data variables are named the same, then you can try the following:
fileName={'ta','te','ti','to','tu'};
for i=1:length(fileName)
dummy=load(sprintf('%s.txt',fileName{i}));
eval(sprintf('data=dummy.%s',fileName{i}));
<other stuff here>
end
I want to mark each value that comes out of my loop with a value.
Say I have a variable number of values that come out of each iteration. I want those values to be labeled by which iteration they came out of.
like
1-1,
2-1,
3-1,
1-2,
2-2,
3-2,
4-2,
etc.
where the first number is the value from the loop and the second is counting which iteration it came from.
I feel like there is a way I just cant find it.
ok so here is some code.
for c=1:1:npoints;
for i=1:1:NN;
if ((c-1)*spacepoints)<=PL(i+1) && ((c-1)*spacepoints)>=PL(i);
local(c)=((c)*spacepoints)-PL(i);
end
if ((c-1)*spacepoints)>=PL(NN);
local(c)=((c)*spacepoints)-PL(NN);
element(i)=NN;
end
end
I want to mark each local value with the iteration it came from for the i:NN. PL is a vector and the output is a set of vectors for each iteration.
For this sort of quick problem I like to create a cell array:
for k = 1:12
results{k} = complicated_function(...);
end
If the output is really complicated, then I return a struct with fields relating to the outputs:
for k = 1:12
results{k}.file = get_filename(...);
results{k}.result = ...;
end
Currently as it is right now, in your inner 1:NN loop, your local(c) variable is being updated or overwritten. You never apply the previous value of local, so it is not some iterative optimization algorithm(?)...
Perhaps an easy solution is to change the size/type of local from a vector to a matrix. Let's say that local is of size [npoints 1]. Instead you make it of size [npoints NN]. It is now a 2d-array (a matrix of npoints rows and NN columns). use the second dimension to store each (assumed column) vector from the inner loop:
local = zeros([npoints NN]);
%# ... code in bewteen ...
for c=1:1:npoints;
for i=1:1:NN;
if ((c-1)*spacepoints)<=PL(i+1) && ((c-1)*spacepoints)>=PL(i);
local(c, i)=((c)*spacepoints)-PL(i);
end
if ((c-1)*spacepoints)>=PL(NN);
local(c, i)=((c)*spacepoints)-PL(NN);
element(i)=NN;
end
end
end
The c'th row of your local matrix will then corresponds to the NN values from the inner loop. Please note that I have assumed your vector to be a column vector - if not, just change the order of the sizes.