MatLab - Error using run => Input argument is undefined - matlab

As a MatLab newbie, I have problems running the following script:
function [ newarray ] = reshapeIm( array, period )
%reshapeIm(array, period) Summary of this function goes here
% Detailed explanation goes here
le = length(array);
fra = le/period;
array = [array, zeros(1, ceil(fra)*period-le)];
newarray = reshape(array', period, []);
end
load('1200rpm_shak3.mat');
cRounds = 54;
mylength = 100;
thetas = (1:cRounds*mylength).*2*pi/mylength;
thetas0 = (1:mylength).*2*pi/mylength;
figure;
plot(z1(1:300), '.-');
plot(z2(1:300), '.-');
z1s = z1;
z2s = [z2(mylength/4+1:end) z2(1:mylength/4)];
z3s = [z3(mylength/2+1:end) z3(1:mylength/2)];
z4s = [z4(mylength*3/4+1:end) z4(1:mylength*3/4)];
dr = 1/4.*(z1s+z2s+z3s+z4s); % gemittelt
drs = reshapeIm(dr, mylength);
drs_std = std(drs, 1, 2);
drs_meanstd = mean(drs_std);
figure;
polar(thetas, 250000+200*dr);
figure;
polar(thetas0', 250000+200*mean(drs,2));
The command window says:
??? Error using ==> run
Input argument 'array' is undefined.
I suppose, that's because the script was written for a newer MatLab, but I use 5.3.

Functions need to be in their own files. You cannot define functions within a script file. So, to get your code to work at all, you need to move the function that is at the top of your file (which I copied below) into its own file. Name the file "reshapeIM.m" and save it in the same directory where you are doing your work.
function [ newarray ] = reshapeIm( array, period )
%reshapeIm(array, period) Summary of this function goes here
% Detailed explanation goes here
le = length(array);
fra = le/period;
array = [array, zeros(1, ceil(fra)*period-le)];
newarray = reshape(array', period, []);
end
Then, after removing the function from your script, save your script and run it again. This should solve the problem with regards to the function. You may have other errors, but this should take care of the error that you reported.

Related

Parallelizing MATLAB code

Hello I want to use parallelize my MATLAB code to run High computing server. It is code to make image database for Deep learning. To parallelize the code I found the I have to for parfor loop. But I used that with the first loop or with the second loop it shows me error parfor cannot be run due to the variable imdb and image_counter. Anyone please help me to change the code to work with parfor
for i = 1:length(cur_images)
X = sprintf('image Numb: %d ',i);
disp(X)
cur_image = load(cur_images{i,:});
cur_image=(cur_image.Image.crop);
%----------------------------------------------
cur_image = imresize(cur_image, image_size);
if(rgb < 1)
imdb.images.data(:,:,1,image_counter) = cur_image;
else
imdb.images.data(:,:,1,image_counter) = cur_image(:,:,1);
imdb.images.data(:,:,2,image_counter) = cur_image(:,:,2);
imdb.images.data(:,:,3,image_counter) = cur_image(:,:,3);
imdb.images.data(:,:,4,image_counter) = cur_image(:,:,4);
imdb.images.data(:,:,5,image_counter) = cur_image(:,:,5);
imdb.images.data(:,:,6,image_counter) = cur_image(:,:,6);
imdb.images.data(:,:,7,image_counter) = cur_image(:,:,7);
imdb.images.data(:,:,8,image_counter) = cur_image(:,:,8);
imdb.images.data(:,:,9,image_counter) = cur_image(:,:,9);
imdb.images.data(:,:,10,image_counter) = cur_image(:,:,10);
end
imdb.images.set( 1,image_counter) = set;
image_counter = image_counter + 1;
end
The main problem here is that you can't assign to fields of a structure inside parfor in the way that you're trying to do. Also, your outputs need to be indexed by the loop variable to qualify as "sliced" - i.e. don't use image_counter. Putting this together, you need something more like:
% Make a numeric array to store the output.
data_out = zeros([image_size, 10, length(cur_images)]);
parfor i = 1:length(cur_images)
cur_image = load(cur_images{i, :});
cur_image=(cur_image.Image.crop);
cur_image = imresize(cur_image, image_size);
% Now, assign into 'data_out'. A little care needed
% here.
if rgb < 1
data_tmp = zeros([image_size, 10]);
data_tmp(:, :, 1) = cur_image;
else
data_tmp = cur_image;
end
data_out(:, :, :, i) = data_tmp;
end
imdb.images.data = data_out;

How to adjust the size of block.outputport.data in Matlab?

I have tried to generate a square pulsed clock. But it gives error. I tried this:
function pll( block)
setup(block);
function setup(block)
% Register number of ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
% Override input port properties
block.InputPort(1).Dimensions = 1;
block.InputPort(1).DatatypeID = 8; % boolean
block.InputPort(1).Complexity = 'Real';
block.InputPort(1).DirectFeedthrough = false;
% Override output port properties
block.OutputPort(1).Dimensions = 1;
block.OutputPort(1).DatatypeID = 0; %double
block.OutputPort(1).Complexity = 'Real';
block.NumDialogPrms = 1;
block.DialogPrmsTunable = 0;
ts = 1/24000000'; %'
block.sample times= [ts 0];
block.SimStateCompliance = 'DefaultSimState'
function Outputs(block)
t = [0:1/(24000000):0.000001];
l = 0.1*exp(-6);
c = 220*exp(-9) + 60*exp(-9);
f = 1/(2*pi*sqrt(l*c));
block.OutputPort(1).Data = square(2*pi*f*t);
function Terminate(block)
But it gives me the error
"Error evaluating registered method 'Outputs' of M-S-Function 'pll' in
'untitled/Level-2 M-file S-Function'. Invalid assignment in
'untitled/Level-2 M-file S-Function': attempt to assign a vector of
width 24001 to a vector of width 1."
the error indicates on the line
block.OutputPort(1).Data = square(2*pi*f*t);
so what can be done to overcome this error?
It seems from your example that you're not really familiar with the way Simulink works. At each time step, each block in a Simulink model outputs a value (i.e the block's output value) corresponding to the current simulation time. In your case, within the block.Output function you are trying to output all time points at every simulation time step.
It appears that what you really want is to replace
t = [0:1/(24000000):0.000001];
with
t = block.CurrentTime;
And replace
block.OutputPort(1).Data = square(2*pi*f*t);
with
block.OutputPort(1).Data = sign(sin(2*pi*f*t));
Also, some other things to consider:
you don't seem to be registering the block's output method using:
block.RegBlockMethod('Outputs',#Output);
Why have you defined the block to have an input when it doesn't seem to require one?
Why are you doing this in an S-Function when a From Workspace block (or one of the many other ways to get data into a model) would seem to make more sense?

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

Conversion function for 3D value into 2D in MATLAB

I have written a function for converting 3D values into 2D, but not able to get it working may be I am parsing the wrong values.
I am passing the value in the valuse as 2 coordinates and trying to get into Output in 2D. Can anyone please do the correction in the function below and help me in running the function?
% Perspective Projection
function Output = perspective_projection(Input)
Output = zeros(size(Input));
for ii = 1: length(Input)
Output(ii,1) = Input(ii,1)/Input(ii,3);
Output(ii,2)=Input(ii,2)/Input(ii,3);
end
value = [6,4,2];
[a1,b1] = perspective_projection(a1)
BSXFUN method as suggested by Rody is an elegant way, but if you would like to keep your loop, try this -
% Perspective Projection
function Output = perspective_projection(Input)
Output = zeros(size(Input,1),2);
for ii = 1: size(Input,1)
Output(ii,1) = Input(ii,1)/Input(ii,3);
Output(ii,2) = Input(ii,2)/Input(ii,3);
end
If I understand you correctly, you should rewrite your function as:
function Output = perspective_projection(Input)
Output = bsxfun(#rdivide, Input(:,1:2), Input(:,3));
end
or, judging from the way you seem to be calling it:
function [OutputX,OutputY] = perspective_projection(Input)
OutputX = Input(:,1)./Input(:,3);
OutputY = Input(:,2)./Input(:,3);
end
Note that your function is quite simple (I wouldn't even use a function):
[X,Y] = deal(Input(:,1)./Input(:,3), Input(:,2)./Input(:,3));
As for your original function: the error is in the initialization:
function Output = perspective_projection(Input)
%// WRONG: this initializes a 3D array!
Output = zeros(size(Input));
%// ...but you want a 2D array
for ii = 1: length(Input)
Output(ii,1) = Input(ii,1)/Input(ii,3);
Output(ii,2) = Input(ii,2)/Input(ii,3);
end
end
and of course, the multiple outputs (but it's not quite clear to me whether you want that or not...)

Undefined function or variable using parfor in matlab

I'm unable to execute the following code:
parallel_mode = true; %To process multiple images at the same time
parallel_degree = 4; %Number of threads that will be created
if parallel_mode
if matlabpool('size') == 0
matlabpool(parallel_degree);
elseif matlabpool('size') ~= parallel_degree
matlabpool close;
matlabpool(parallel_degree);
end
end
%Loading dictionary
try
load(dictionary_path);
catch
error(['Was impossible to load the dictionary in path: ' dictionary_path ', Please, check the path. ' ...
'Maybe you should use dictionary_training function to create it.'])
end
%% Processing test images
test_images = dir([test_im_path, pattern]);
num_test_images = size(test_images,1);
%Pre-allocating memory to speed-up
estimated_count = zeros(1,num_test_images);
true_count = zeros(1,num_test_images);
estimated_upper_count = zeros(1,num_test_images);
estimated_lower_count = zeros(1,num_test_images);
true_upper_count = zeros(1,num_test_images);
true_lower_count = zeros(1,num_test_images);
%Calculating dimensions of the image subregion where we can count
im_test = imread([test_im_path test_images(1).name]);
dis = round(patch_size/2);
dim_x = dis:size(im_test,2)-dis+1;
dim_y = dis:size(im_test,1)-dis+1;
toGaussian = fspecial('gaussian', hsize, sigma);
parfor a=1:num_test_images
disp(['Processing image #' num2str(a) ' of ' num2str(num_test_images) '...']);
im_test = imread([test_im_path test_images(a).name]);
[~, name, extension] = fileparts(test_images(a).name);
im_ground_truth = imread([ground_truth_path name 'dots' extension]);
disp('Extracting features...');
features = extract_features(im_test, features_type, dic_signal, sparsity, patch_size, mean_rem_flag);
features = full(features); %ND-sparse arrays are not supported.
%Re-arranging features
features = reshape(features', size(dim_y,2), size(dim_x,2), dic_size);
%Normalizing features
max_factors_3D = repmat(max_factors_depth, [size(features,1), size(features,2)]);
max_offset_3D = repmat(max_offset_depth, [size(features,1), size(features,2)]);
features = (features-max_offset_3D)./max_factors_3D;
%%Some stuff
....
end
When i execute it i get:
Undefined function or variable 'dic_signal'.
when it arrives to the extract_features function. However, in the single thread version (with for instead of parfor) it works correctly.
Someone can give me any hint?.
Thank you.
EDIT:
dic_signal is defined and correctly loaded in load(dictionary_path);
I suspect the load command doesn't load the variables in the workers workspace, only on your MATLAB instance workspace, which is why it works in a normal for loop, but not with a parfor loop. You might want to try instead:
pctRunOnAll load(dictionary_path)
to ensure the correct data is loaded into the workspace of each of the workers.