Conversion to struct from double is not possible - matlab

I have two questions
(1) Why is the following code generating this error ? where does double come from?
Error using horzcat
The following error occurred converting from double to struct:
Error using struct
Conversion to struct from double is not possible.
Error in remove_scratch (line 34)
old1 = [lines1, max_vertex1] ;
(2) how to get rid of this error?
Relevant Source Code
for n = 1:N
% take n-th image
hough_trf_input = monochrome_image(:,:,n);
% find straight lines in the image
[hough_lines, thetas] = hugh_transform(hough_trf_input);
%////////////////////////////////////////////////////////////
[lines1, max_vertex1] = find_lines(hough_lines, thetas(1));
[lines2, max_vertex2] = find_lines(hough_lines, thetas(2));
[lines3, max_vertex3] = find_lines(hough_lines, thetas(3));
if(n==1)
old1 = [lines1, max_vertex1];
old2 = [lines2, max_vertex2];
old3 = [lines3, max_vertex3];
else
oldlen1 = vertex_length(old1(2));
oldlen2 = vertex_length(old2(2));
oldlen3 = vertex_length(old3(2));
newlen1 = vertex_length(max_vertex1);
newlen2 = vertex_length(max_vertex2);
newlen3 = vertex_length(max_vertex3);
if(newlen1 > oldlen1)
old1 = [lines1, max_vertex1] ;
end
if(newlen2 > oldlen2)
old2 = [lines2, max_vertex2] ;
end
if(newlen3 > oldlen3)
old3 = [lines3, max_vertex3] ;
end
end
end
Here find_lines() returns a vector whose 1st element is a vector of line-structs, and the second element is a vector of two vectors where each vector is 2-element and represents an axis.

one of the variables {lines1, max_vertex1} is struct and the other is double. from their names I guess lines1 is struct and max_vertex1 is double. You can obtain the same error when running:
clear
% lines1 is struct
lines1.p1 = 1;
lines1.p2 = 1;
% max_vertex1 is double
max_vertex1 = 5;
old1 = [lines1, max_vertex1] ;
There are several ways to overcome this, for example you can extract the struct fields into double using struct2array:
old1 = [struct2array(lines1), max_vertex1] ;

Related

Fibonacci Function in MATLAB

I am attempting to create a function for the Fibonacci numbers using a for loop. My code is as follows:
function fib = fibGenerator(N)
fib(1) = 0;
fib(2) = 1;
for i = 3:N
fib(i) = fib(i-1)+fib(i-2);
end
The following error message is displayed: Variable fib must be of data type uint32. It is currently of type double. Check where the variable is assigned a value.
I'm unsure of how to correct this.
Update
function fib = fibGenerator(N)
fibGenerator(1) = uint32(0);
fibGenerator(2) = uint32(1);
for i = 3:N
fibGenerator(i) = fibGenerator(i-1)+fibGenerator(i-2);
end
You have to cast when you initially create fib: fib(1) = uint32(0);
Here is an example demonstrating this. When creating x you decide the type. Even if later assignments are double or of other types, it will keep its type.
>> x=uint32(1)
x =
uint32
1
>> x(2)=double(2)
x =
1×2 uint32 row vector
1 2

Matlab error limitin bounds

I get the following error when I try to run this code "Attempted to access id(90); index out of bounds because numel(id)=89.Error in Untitled66 (line 26) person = find(id(fileNum)==ids);" Can someone help me spot the error?
% File Names reading and label generation
dataFolder= 'allcontent/';
fileNames = dir([dataFolder 'c*.*']);
lbl = sscanf(cat(1,fileNames.name)','co2%c%d.rd_%d.mat');
status = lbl(1:3:end);
id = lbl(2:3:end);
ids = unique(id);
trial = lbl(3:3:end);
%% File reading and Data Generation
%data = 256*channel*trial*stimulus*id
trData = zeros(256,64,10,3,20,'single');
label = zeros(10,3,20,'single');
trials = ones(3,20);
for fileNum = 1:numel(fileNames)
fin = fopen([dataFolder fileNames(fileNum).name]);
for i=1:4
line= fgetl(fin);
end
a= sscanf(line,'%S%d %s , trial %d');
stimulus = (3-numel(a));
person = find(id(fileNum)==ids);
trialNum = trials(stimulus, person);
label (trialNum, stimulus, person) = status(fileNum);
fprintf('%d %d %d\n', person,trialNum, stimulus);
for ch=1: 64
fgetl(fin);
curData = textscan(fin,'%d %s %d %f');
trData(:,ch,trialNum,stimulus,person) = curData{4};
end
for fileNum = 1:numel(fileNames) iterates over all files, but you don't have an id for each file: id = lbl(2:3:end);.
It seems to me that you want to iterate only over 1/3 or the files?
for fileNum = 2:3:numel(fileNames)
It's hard to tell what you're trying to accomplish, though. Are files related in groups of 3? You're probably better off selecting files from their names before computing id and all the other support matrices.

MATLAB: Find function within range

How can I use the find function within specific ranges.
Say, I have an array arr1 with random values. I have the start & end indices of the portions I'd like to analyze (in this example, I want to find the first occurrence for when the value is larger than 0.8)
How could the find function be used here with start and end indices and the condition as well?
For example:
arr1 = rand(1000,1);
start_ind = [100;500;850];
end_ind = [160;620;925];
for i = 1:length(start_ind)
output = find(arr1(start_ind(i):end_ind(i)) >=0.8); % ????
end
Much appreciated,
Use the second argument of find to only get the first match. You can then shift indices by adding start_ind - 1:
arr1 = rand(1000,1);
start_ind = [100; 500; 850];
end_ind = [160; 620; 925];
output = zeros(length(start_ind), 1);
for i = 1:length(start_ind)
output(i) = find(arr1(start_ind(i):end_ind(i)) >=0.8, 1) + start_ind(i) - 1;
end

Matlab and "Error while evaluating UIcontrol callback"

I have a matlab file that I can't post here (3000 lines) which contains a lot of functions which are used from a GUI.
I am working with matlab file that contains the 3000 lines which has so many functions for design GUI
when I am using Function A that function which are related to uses the several other functions and make it as for loop that run many time function A (1600-2000) times of iterations through taking a long time.
when I reached at 400-500 Matlab gives me
error : "Error while evaluation UIcontrol callback"
I must to kill the existing process and then exit Matlab and run again from the previous iteration which give the error. So my problem is not based on the function call but it may comes based on memory or may be temporary memory.
Does it possible to increase the temporary memory uses by Matlab ?
I increase the preference "Java heat memory" at maximum but this preference change nothing to my problem.
Is there any way to solve this issue ?
A part of the script :
function CalculateManyOffset % It's Function A on this topic
mainfig = FigHandle;
parameters = get(mainfig,'UserData');
dbstop if error
NumberofProfiles = str2double(get(parameters.NumberofProfilesBox,'string'));
step = str2double(get(parameters.DistBetweenProfilesBox,'string'));
Alphabet=('A':'Z').';
[I,J] = meshgrid(1:26,1:26);
namered = [Alphabet(I(:)), Alphabet(J(:))];
namered = strvcat(namered)';
nameblue = [Alphabet(I(:)), Alphabet(J(:))];
nameblue = strvcat(nameblue)';
apostrophe = '''';
SaveNameDisplacementFile = [get(parameters.SaveNamebox,'string'),'.txt'];
a=0;
icounter = 0;
StartBlue = str2double(get(parameters.bluelinebox,'String'));
EndBlue = StartBlue + NumberofProfiles;
StartRed = str2double(get(parameters.redlinebox,'String'));
EndRed = StartRed + NumberofProfiles-15;
for i = StartBlue:step:EndBlue;
icounter = icounter +1;
jcounter = 0;
for j=StartRed:step:EndRed;
jcounter = jcounter +1;
opthorz = [];
maxGOF = [];
a=[a(1)+1 length(StartRed:step:EndRed)*length(StartBlue:step:EndBlue)]
%
if a(1) >= 0 && a(1) <= 20000
BlueLineDist = 1*i;
parameters.bluelinedist = i;
RedLineDist = 1*j;
parameters.redlinedist = j;
parameters.i = icounter;
parameters.j = jcounter;
set(mainfig,'UserData',parameters,'HandleVisibility','callback'); % To update variable parameters for the function which use them (downside : BlueLine, RedLine, GetBlueProfile, GetRedProfile, CalculateOffset)
BlueLine;
RedLine;
GetBlueProfile;
GetRedProfile;
CalculateOffset;
% Now, reload variable parameters with new value calculate on previous functions
mainfig = FigHandle;
parameters = get(mainfig,'UserData');
opthorz = parameters.opthorz;
name = [num2str(namered(:,jcounter)'),num2str(nameblue(:,icounter)'),apostrophe];
namefid2 = [num2str(namered(:,jcounter)'),' - ',num2str(nameblue(:,icounter)'),apostrophe];
Distance = [num2str(RedLineDist),' - ',num2str(BlueLineDist)];
maxGOF = parameters.maxGOF;
% Create file with all displacements
if a(1) == 1;
fid2 = fopen(SaveNameDisplacementFile,'w');
fprintf(fid2,['Profile red - blue\t','Distance (m) between profile red - blue with fault\t','Optimal Displacement\t','Goodness of Fit\t','20%% from Goodness of Fit\t','Minimal Displacement\t','Maximal Displacement \n']);
fprintf(fid2,[namefid2,'\t',Distance,'\t',num2str(opthorz),'\t',num2str(maxGOF),'\t',num2str(parameters.ErrorGOF),'\t',num2str(parameters.ErrorDisp(1,1)),'\t',num2str(parameters.ErrorDisp(1,2)),'\n']);
elseif a(1) ~= b(end);
fid2 = fopen(SaveNameDisplacementFile,'a');
fprintf(fid2,[namefid2,'\t',Distance,'\t',num2str(opthorz),'\t',num2str(maxGOF),'\t',num2str(parameters.ErrorGOF),'\t',num2str(parameters.ErrorDisp(1,1)),'\t',num2str(parameters.ErrorDisp(1,2)),'\n']);
else
fid2 = fopen(SaveNameDisplacementFile,'a');
fprintf(fid2,[namefid2,'\t',Distance,'\t',num2str(opthorz),'\t',num2str(maxGOF),'\t',num2str(parameters.ErrorGOF),'\t',num2str(parameters.ErrorDisp(1,1)),'\t',num2str(parameters.ErrorDisp(1,2))]);
fclose(fid2);
end
end
end
end

Error of declaration of variable

I have a problem at the beginning of my function. The function is to combine several data column from some objects. Error happens at the beginning of function. It says as follows:
Error in find_by_coor (line 2)
for i = 1:length(obj_ac)
Here is only the declaration of variable and loop, but Matlab somehow returned error. I have no idea so would like someone to help me. I attached my code as follows. Thanks a lot in advance.
function arr = find_by_coor(obj_ac,obj_gps,obj_sen_dir,lat1,long1,lat2,long2)
for i = 1:length(obj_ac)
if eq(obj_sen_dir(i).sensor,4) && strcmp(obj_sen_dir(i).direction,'outbound')
ind = obj_gps(i).save_var_gps(:,1)>lat1;
if isempty(find(ind)) == 1
continue
end
temp = obj_gps(i).save_var_gps(ind,:);
ind = temp(:,1)<lat2;
if isempty(find(ind)) == 1
continue
end
temp2 = temp(ind,:);
ind = temp2(:,2)<long1;
if isempty(find(ind)) == 1
continue
end
temp3 = temp2(ind,:);
ind = temp3(:,2)>long2;
if isempty(find(ind)) == 1
continue
end
temp4 = temp3(ind,:);
mint = min(temp4(:,5))-min(obj_gps(i).save_var_gps(:,5));
maxt = max(temp4(:,5))-min(obj_gps(i).save_var_gps(:,5));
if isempty(mint) == 1 || isempty(maxt) == 1
continue
end
if floor(mint*(1.6516e+03)) == 0 || floor(maxt*(1.6516e+03)) == 0
continue
end
temp5 = obj_ac(i).save_var(floor(mint*(1.6516e+03)):floor(maxt*(1.6516e+03)));
temp6 = abs(fft(temp5));
arr(i,:) = [i objs(i).daten var(temp5) max(temp5) min(temp5) mean(temp5) std(temp5) mode(temp5) var(temp6) max(temp6) min(temp6) mean(temp6) std(temp6) mode(temp6)];
disp(i);
end
end
end
The problem is that when you run the function, the output variable arr is never assigned. In Matlab you must always assign a function output if you choose to have it in the definition. For example
function [a,b] = setAB()
err = 0; % Gives an error if err is true
a = 1;
if ~err
b = 1;
end
The reason is most certainly that for some inputs, all values fall into one of the if statements and you do never reach the point where arr is assigned. A good solution for this is to assign a default value for arr in the beginning. That may for example be nan or -1 or, in your case maybe an array arr = nan(wanted size) or arr = -1*ones(wanted size). If you do not preallocate arr you will likely get a "matrix out of bounds" error instead, should you solve the first issue.
It does not mean that you always need to have an output though.
function [] = noOutput()
disp('Hi, I am a void!');
You may also choose to return as many values as number of outputs.
function varargout = variableArgs()
a = 1;
b = 2;
c = 3;
if (nargout == 1)
varargout{1} = a;
elseif (nargout == 2)
varargout{1} = b;
varargout{2} = c;
else
error('Wrong number of output arguments!');
end
I am not saying which of the approaches you should use or that any of them are good. Normally I use varargout in case I write plotting functions. Then I may want to return nothing in case I do not have an output argument. Then I want to return handles or any extra information. Further as you may have understood there is also a varargin that may be of more use.