Matlab saving without losing previous iteration's value - matlab

i'm trying to save values of iterations in a loop. After this function, they will execute other functions before coming to the next iteration. But the problem i'm facing is, it overwrites them and bcomes 000000. Only the last iteration values are seen. How can i fix it ? Is there a way not to use the same variable and save them ? i read about append but will have to use different var name n is not really nice to do so.
function DistanceMatrix(iteration,distance_row)
load('data.mat','oridata')
load('centroids.mat','centroids')
for i = distance_row:(distance_row+3)
for j=1:300 %no.genes
total=0;
for k=1:6
total=total+((oridata(j,k)- centroids(i,k))^2);
end
DistMatrix_Val(i,j)=sqrt(total);
end
end
save('DistanceMatrix.mat','DistMatrix_Val')
DistMatrix_Val;
GroupMatrix(iteration,distance_row)
end
This is the output. I WOULD LIKE TO STORE ALL ITERATION's value and not overwrite them. Can any1 help ?

OK. Use
load('DistanceMatrix.mat','DistMatrix_Val')
or
persistent DistMatrix_Val
just before the first load command you showed to us.

I think this is what you should do:
functon DistanceMatrix = DistanceMatrix(iteration,distance_row)
Rather than saving the variable at the end of the function, you return it.
After returning it you can include the variable in a bigger variable (for example a three dimensional Nx4x300 matrix)
If neccesary you can then save it at the end.

Related

Callback sharing data in Matlab

I have being to share data between several callback options in Matlab, however no succes so far. I have a gui with multiple tables which I use to get the input from the user. I have multiple callback functions for the different tables. I would like to use the data from table 1 and callback 1 together with the date in table 2 in callback two.
function MaterialProperties(Material, Data)
Material_data = get(Material, 'Data');
% Avoid bluehighlight in table
set(Material,'Data',{'dummy'});
set(Material,'Data', Material_data);
% Store variable in workspace
assignin('base','Material_data',Material_data)
%Mat_data = guidata(gcbo);
%for i=1:size(Material_data,2)
% Mat_data.MatData{i}=Material_data{i};
%end
% Save the change you made to the structure
guidata(gcbo,Mat_data)
assignin('base','Mat_data',Mat_data)
end
function Stacking_sequence(Layup, Data)
% I want to use the date (Material_data) of MaterialProperties here in this callback
layup_data = get(Layup, 'Data');
%overwrite data with a dummy and restore the old data afterwards, to force deselection
set(Layup,'Data',{'dummy'});
set(Layup,'Data', layup_data );
%store variable in workspace
assignin('base','layup_data',layup_data)
layup = strsplit(layup_data{1,1},'\');
assignin('base','layup',layup)
end
Can anyone help. I tried theMatlab help, but the suggestions stated there didn't work (maybe I implemented it wrong)
It looks like you simply need to retrieve the handles structure at the beginning of callback 2, like you did in the first callback:
Mat_data = guidata(gcbo);
after which it should be available in the 2nd callback. By the way this very line and the 3 lines following it are commented in your code is that a mistake?
Alternative solution:
As an alternative solution, you can use setappdata/getappdata to share data between function callbacks as well as in the command window, depending on where you store those data.
For example, if you save Material_data at the end of the 1st callback using something like this:
setappdata(0,'MatData',Material_Data); % Save in the Matlab root 0 (accessible everywhere), and give some dummy name)
Then at the beginning of the 2nd callback, you can retrieve the data using getappdata:
Material_Data = getappdata(0,'MatData');
and you're good to go. Instead of using the 0 root, you could also store the data in the GUI itself, using for example handles.FigureGUI or whatever the name of the figure is. Then the data would be available only if the figure is not closed/deleted. Play around with those and see what you prefer.
Hope that helps!

Matlab bad cell reference operation when if statement

I have a <850x1> cell called x. Each of the individual structures has a 'Tag' name and 'Data' cell with <7168x1 double> data values.
(i.e.
x{1,1}.Tag = 'Channel1', x{1,1}.Data= <7168x1 double>)
So, I want to go through the x cell, identify the structures with 'Channel1' Tag names and pull out that structure's data. Then, combine the data into a cell called Ch1. Here is my approach so far:
n=1:850
if x{n,1}.Tag == 'Channel1'
Ch1{:,n} = x{n,1}.Data;
end
However, this gives an error: Bad cell reference operation.
Any ideas what may be going wrong?
There are 2 issues here. First, your if statement will compare each entry in the string x{n,1}.Tag to each entry in the string 'Channel1'. If the dimensions are not the same, you will get an error. To fix this, you could use the string compare function, strcmp. The other issue is that you are assigning n to all values between 1 and 850 at once. This is the issue that is producing the actual error you are seeing. Instead, you want to step through each of these values one at a time with a for loop. I would suggest trying the following code:
for n=1:850
if strcmp(x{n,1}.Tag, 'Channel1')
Ch1{:,n} = x{n,1}.Data;
end
end

Debugging a for loop in matlab

I've been looking throught the documentation, but can't seem to find the bit I want.
I have a for loop and I would like to be able to view every value in the for loop.
for example here is a part of my code:
for d = 1 : nb
%for loop performs blade by blade averaging and produces a column vector
for cc = navg : length(atbmat);
atb2 = (sum(atbmat((cc-(navg-1):cc),d)))/navg;
atbvec2(:,cc) = atb2;
end
%assigns column vector 'atbvec2' to the correct column of the matrix 'atbmat2'
atbmat2(d,1:length(atbvec2)) = atbvec2;
end
I would like to view every value of atb2. I'm a python user(new to MATLAB) and would normally use a simple print statement to find this.
I'm sure there is a way to do it, but I can't quite find how.
Thankyou in advance.
you can use disp in Matlab to print to the screen but you might want to use sprintf first to format it nicely. However for debugging you're better off using a break point and then inspect the variable in the workspace browser graphically. To me, this is one of Matlab's best features.
Have a look at the "Examine Values" section of this article
The simplest way to view it everywhere is to change this line:
atb2 = (sum(atbmat((cc-(navg-1):cc),d)))/navg;
Into this, without semicolon:
atb2 = (sum(atbmat((cc-(navg-1):cc),d)))/navg
That being said, given the nature of your calculation, you could get the information you need as well by simply storing every value of abt2 and observing them afterwards. This may be done in atbmat2 already?
If you want to look at each value at the time it happens, consider setting a breakpoint or conditional breakpoint after the line where abt2 is assigned.

How to rename a variable in a loop in MATLAB?

Can somebody please tell if there exists a way to rename a variable in each iteration of a loop in MATLAB?
Actually, I want to save a variable in a loop with a different name incorporating the index of the loop. Thanks.
Based on your comment, I suggest using a cell array. This allows any type of result to be stored by index. For example:
foo=cell(bar,1);
for ii=1:bar
foo{ii}=quux;
end
You can then save foo to retain all your intermediate results. Though the loop index is not baked into the variable name as you want, this offers identical functionality.
Ignoring the question, "why do you need this?", you can use the eval() function:
Example:
for i = 1:3
eval(['val' num2str(i) '=' num2str(i * 10)]);
end
The output is:
val1 =
10
val2 =
20
val3 =
30
Another way, using a struct to save the loop index into the name of the field:
for ii=1:bar
foo.(["var" num2str(ii)]) = quux;
end
This creates a structure with fields like foo.var1, foo.var1 etc. This does what you want without using eval.

Matlab: How to remove the error of non-existent field

I am getting an error when running matlab code. Here I am trying to use one of the outputs of previous code as input to my new code.
??? Reference to non-existent field 'y1'.
Can anyone help me?
A good practice might be to check if the field exists before accessing it:
if isfield( s, 'y1' )
% s.y1 exists - you may access it
s.y1
else
% s.y1 does not exist - what are you going to do about it?
end
To take Edric's comment into account, another possible way is
try
% access y1
s.y1
catch em
% verify that the error indeed stems from non-existant field
if strcmp(em.identifier, 'MATLAB:nonExistentField')
fprintf(1, 'field y1 does not exist...\n');
else
throw( em ); % different error - handle by caller?
end
end
Have you used the command load to load data from file(s)?
if yes, this function overwrite your current variables, therefore, they become non-existent, so when you call, it instead of using:
load ('filename');
use:
f=load ('filename');
now, to refer to any variable inside the loaded file use f.varname, for
example if there is a network called net saved within the loaded data you may use it like:
a = f.net(fv);
I would first explain my situation and then give the solution.
I first save a variable op, it is a struct , its name is coef.mat;
I load this variable using coef = load( file_path, '-mat');
In a new function, I pass variable coef to it as a parameter, at here, the error Reference to non-existent field pops out.
My solution:
Just replace coef with coef.op, then pass it to the function, it will work.
So, I think the reason behind is that: the struct was saved as a variable, when you use load and want to acess the origin variable, you need point it out directly using dot(.) operation, you can directly open the variable in Matlab workspace and find out what it wraps inside the variable.
In your case, if your the outputs of previous code is a struct(It's my guess, but you haven't pointed out) and you saved it as MyStruct, you load it as MyInput = load(MyStruct), then when use it as function's parameter, it should be MyInput.y1.
Hops it would work!
At first load it on command window and observe the workspace window. You can see the structure name. It will work by accessing structure name. Example:
lm=load('data.mat');
disp(lm.SAMPLE.X);
Here SAMPLE is the structure name and X is a member of the structure