MATLAB | How to use the result from exist? - matlab

I am doing a basic MATLAB online-course and in one part of the last assignment I need to "create a line graph from an expression based on user input".
My interpretation is that a user should be able to type in an expression f(x)=... such as:
3x^2+3x+c
I have successfully written code that will ask the user for the number of variables (numbers before the x:s) and exponents and if there is an constant or not.
Also, my code then generates variables from user input (input: string -> genvarname), and then assigns a correct value to it also from user input via the eval command/function.
Lastly, I have done an for-loop and used exist to determine if a variable exists.
My question now is, how can I use the result from exist (eg = 1) in a if-loop to access the variable and store it in an vector.
That way I believe I can with another for loop calculate values for y. the x-values are just x = -50:1:50, but if there are any suggestions for how to calculate y simpler than please tell me.
I have gained lots of information from reading StackOverflow posts, I just hope my question is relevant, and helpful. :)
EDIT:
%% Initial questions
IN = input('Give foo: [på formen A1x^a1+A2x^a2...Nx^n+KONST] ','s');
if isempty(IN)
IN = '3x^2+4x+2';
end
disp(['Du vill plotta ' IN]);
vars_qty = input('Hur många variabler har du? ');
if isempty(vars_qty)
vars_qty = 2;
end
exps_qty = vars_qty;
const = input('Har du en konstant på slutet? [Ja/Nej] ','s');
if isempty(const)
const = 'Ja';
end
disp(' ');
%vars_vector_name = cell(vars_qty, 1); % cell array with variable names
vars_vector_vals = zeros(vars_qty, 1); % vector with variable values
%exps_vector_name = cell(exps_qty, 1); % cell array with exponent names
exps_vector_vals = zeros(exps_qty, 1); % vector with exponent values
%% Assigning vectors
x = -50:1:50; % x vector
A = zeros(vars_qty, 1);
a = zeros(vars_qty, 1);
%% Assigning variable and exponent names + create variables and set a value to it
for i = 1:vars_qty
disp(['Variabel ' num2str(i) ':']);
% vars_vector_name(i, 1) = cellstr(input('Var god och namnge variabeln [A1,B..] ', 's')); %
... does not like an empty input
var = input('Var god och namnge variabeln [A1,A2...An] ', 's');
% if isempty(var)
% var = ['A',num2str(i)];
% end
vars_vector_vals(i, 1) = input('Vad är värdet på variabeln? '); %
... does not like an empty input
% if isempty(vars_vector_vals(i, 1))
% vars_vector_vals(i, 1) = i;
% end
vars_gen = genvarname( var );
eval([ var '= vars_vector_vals(i, 1);' ]);
vars_exist = exist( ['A',num2str(i)], 'var'); % isvarname( num2str(vars_gen) ); % num2str(vars_gen)
if vars_exist == 1
disp('Exist!');
% A(i, 1) = vars_gen;
% A(i, 1) = eval([ var '= vars_vector_vals(i, 1);' ]);
else
...
end
disp(['Exponent ' num2str(i) ':']);
exps = input('Var god och namnge exponenten [a1,a2...an & a2<a1] ', 's');
% if isempty(exps)
% exp = ['a',num2str(i)];
% end
exps_vector_vals(i, 1) = input('Vad är värdet på exponenten? '); %
... does not like an empty input
% if isempty(exps_vector_vals(i, 1))
% exps_vector_vals(i, 1) = i;
% end
exps_gen = genvarname( exps );
eval([ exps '= exps_vector_vals(i, 1);' ]);
exps_exist = exist( ['a',num2str(i)], 'var'); % isvarname( num2str(exps_gen) ); % num2str(exps_gen)
if exps_exist == 1
disp('Exist!');
% a(i, 1) = exps_gen;
% a(i, 1) = eval([ exps '= exps_vector_vals(i, 1);' ]);
else
...
end
end
% exps_vector_name(j, 1) = cellstr(input('Var god och namnge exponenten [a,b.. & b<a] ', 's')); %
... does not like an empty input
if strcmp(const,'Ja')
disp(' ');
const_scalar = input('Vad är värdet på konstanten? '); % scalar with constant
else
const_scalar = 0;
end
%gen_vars = genvarname({ (vars_vector_name(:,1)) });
%gen_exps = genvarname({ (exps_vector_name(:,1)) });
%eval([ gen_vars '= vars_vector_vals(:,1);' ]); % doesn't like a cell array
%eval([ gen_exps '= exps_vector_vals(:,1);' ]); % doesn't like a cell array
y = zeros(vars_qty, 1);
% for k = 1:vars_qty
% y(k, 1) =
% end

MATLAB's EXIST command is a little tricky to use correctly because it checks so many things. Here's how I would write this:
userVarName = ...
if exist(userVarName, 'var') == 1 % Return value 1 indicates a variable.
varValue = eval(userVarName);
else
error('Variable "%s" does not exist.', userVarName);
end
EDIT
Looks like the relevant portion of your code needs to be adapted like so:
vars_name = ['A', num2str(j)];
if exist(vars_name, 'var') == 1
A(j, 1) = eval(vars_name);
end

Related

High performance computation of mean 2D-Euclidian-distance

Let's say I have a position matrix P with dimensions 10x2, where the first column contains x values and second column the corresponding y values. I want the mean of the lengths of the positions. The way I have done this so far is with the following code:
avg = sum( sqrt( P(:,1).^2 + P(:,2).^2))/10);
I've been told that the integral function integral2 is much faster and more precise for this task. How can I use integral2 to compute the mean value?
Just so this question doesn't remain unanswered:
function q42372466(DO_SUM)
if ~nargin % nargin == 0
DO_SUM = true;
end
% Generate some data:
P = rand(2E7,2);
% Correctness:
R{1} = m1(P);
R{2} = m2(P);
R{3} = m3(P);
R{4} = m4(P);
R{5} = m5(P);
R{6} = m6(P);
for ind1 = 2:numel(R)
assert(abs(R{1}-R{ind1}) < 1E-10);
end
% Benchmark:
t(1) = timeit(#()m1(P));
t(2) = timeit(#()m2(P));
t(3) = timeit(#()m3(P));
t(4) = timeit(#()m4(P));
t(5) = timeit(#()m5(P));
t(6) = timeit(#()m6(P));
% Print timings:
disp(t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Original method:
function out = m1(P)
if DO_SUM
out = sum( sqrt( P(:,1).^2 + P(:,2).^2))/max(size(P));
else
out = mean( sqrt( P(:,1).^2 + P(:,2).^2));
end
end
% pdist2 method:
function out = m2(P)
if DO_SUM
out = sum(pdist2([0,0],P))/max(size(P));
else
out = mean(pdist2([0,0],P));
end
end
% Shortened method #1:
function out = m3(P)
if DO_SUM
out = sum(sqrt(sum(P.*P,2)))/max(size(P));
else
out = mean(sqrt(sum(P.*P,2)));
end
end
% Shortened method #2:
function out = m4(P)
if DO_SUM
out = sum(sqrt(sum(P.^2,2)))/max(size(P));
else
out = mean(sqrt(sum(P.^2,2)));
end
end
% hypot
function out = m5(P)
if DO_SUM
out = sum(hypot(P(:,1),P(:,2)))/max(size(P));
else
out = mean(hypot(P(:,1),P(:,2)));
end
end
% (a+b)^2 formula , Divakar's idea
function out = m6(P)
% Since a^2 + b^2 = (a+b)^2 - 2ab,
if DO_SUM
out = sum(sqrt(sum(P,2).^2 - 2*prod(P,2)))/max(size(P));
else
out = mean(sqrt(sum(P,2).^2 - 2*prod(P,2)));
end
end
end
Typical result on my R2016b + Win10 x64:
>> q42372466(0) % with mean()
0.1165 0.1971 0.2167 0.2161 0.1719 0.2375
>> q42372466(1) % with sum()
0.1156 0.1979 0.2233 0.2181 0.1610 0.2357
Which means that your method is actually the best of the above, by a considerable margin! (Honestly - didn't expect that!)

MATLAB displaying a table [duplicate]

I want to use MATLAB's printmat do display a matrix with labels. But this doesn't work for complex numbers:
N = 5;
x = rand(N,1);
y = rand(N,1);
z = x + 1i*y;
printmat([x,y,z],'fftdemo','N=1 2 3 4 5','x y x+iy');
Output:
fftdemo =
x y x+iy
N=1 0.84072 0.34998 0.84072
2 0.25428 0.19660 0.25428
3 0.81428 0.25108 0.81428
4 0.24352 0.61604 0.24352
5 0.92926 0.47329 0.92926
As you can see the imaginary part of z isn't printed.
Is there a way to get Matlab to display complex numbers or another way to achieve this?
Any print function in matlab will only print real value of imaginary number. TO get both the parts you must call them explicitly.So correct usage would be
printmat([x,y,real(z),imag(z)],'fftdemo','N=1 2 3 4 5','x y x iy');
But this wont be of any use now since both are parts are getting printed twice.
Here is a slightly altered version of printmat that will print complex numbers. Feel free to fiddle around a bit more with it for better looks :)
function [] = printmat2(a,name,rlab,clab)
%PRINTMAT Print matrix with labels.
% PRINTMAT(A,NAME,RLAB,CLAB) prints the matrix A with the row labels
% RLAB and column labels CLAB. NAME is a string used to name the
% matrix. RLAB and CLAB are string variables that contain the row
% and column labels delimited by spaces. For example, the string
%
% RLAB = 'alpha beta gamma';
%
% defines 'alpha' as the label for the first row, 'beta' for the
% second row and 'gamma' for the third row. RLAB and CLAB must
% contain the same number of space delimited labels as there are
% rows and columns respectively.
%
% PRINTMAT(A,NAME) prints the matrix A with numerical row and column
% labels. PRINTMAT(A) prints the matrix A without a name.
%
% See also: PRINTSYS.
% Clay M. Thompson 9-24-90
% Copyright 1986-2002 The MathWorks, Inc.
% $Revision: 1.10 $ $Date: 2002/04/10 06:32:35 $
error(nargchk(1,4,nargin));
space = ' ';
[nrows,ncols] = size(a);
if nargin<2, name = []; end
if nargin==3, error('Wrong number of input arguments.'); end
if nargin<4,
rlab = []; clab = [];
for i=1:nrows, rlab = [rlab, sprintf('--%d--> ',i)]; end
for i=1:ncols, clab = [clab, sprintf('--%d--> ',i)]; end
rlab=rlab(1:length(rlab)-1);
clab=clab(1:length(clab)-1);
end
col_per_scrn=5;
len=12;
if (nrows==0)|(ncols==0),
if ~isempty(name), disp(' '), disp(sprintf('%s = ',name)), end
disp(' ')
disp(' []')
disp(' ')
return
end
% Remove extra spaces (delimiters)
ndx1 = find(clab==' ');
ndx2 = find([ndx1,0]==[-1,ndx1+1]);
if ~isempty(clab), clab(ndx1(ndx2))=[]; end
ndx1 = find(rlab==' ');
ndx2 = find([ndx1,0]==[-1,ndx1+1]);
if ~isempty(rlab), rlab(ndx1(ndx2))=[]; end
% Determine position of delimiters
cpos = find(clab==' ');
if length(cpos)<ncols-1, error('Not enough column labels.'); end
cpos = [0,cpos,length(clab)+1];
rpos = find(rlab==' ');
if length(rpos)<nrows-1, error('Not enough row labels.'); end
rpos = [0,rpos,length(rlab)+1];
col=1;
n = min(col_per_scrn-1,ncols-1);
disp(' ')
if ~isempty(name), disp(sprintf('%s = ',name)), end % Print name
while col<=ncols
% Print labels
s = space(ones(1,len+1));
for j=0:n,
lab = clab(cpos(col+j)+1:cpos(col+j+1)-1);
if length(lab)>len,
lab=lab(1:len);
else
lab=[space(ones(1,len-length(lab))),lab]; end
s= [s,' ',lab];
end
disp(setstr(s))
for i=1:nrows,
s = rlab(rpos(i)+1:rpos(i+1)-1);
if length(s)>len, s=s(1:len); else s=[space(ones(1,len-length(s))),s]; end
s = [' ',s];
for j=0:n,
element = a(i,col+j);
if imag(element) ~= 0
s=[s,sprintf('%12.5f + %12.5fi',[real(element) imag(element)])];
else
if element==0,
s=[s,' 0'];
elseif (element>=1.e6)|(element<=-1.e5)|(abs(element)<.0001)
s=[s,sprintf(' %12.5e',element)];
else
s=[s,sprintf(' %12.5f',element)];
end
end
end
disp(s)
end % for
col = col+col_per_scrn;
disp(' ')
if (ncols-col<n), n=ncols-col; end
end % while
% end printmat

get number of levels of a cell

Well i got the problem, that i have to acces the content of a cell in Matlab. But it's not an ordinary cell. There could be a cell in a cell. And i don't know how many levels the first cell has.
All the cells have the dimension (1,x)
so it could be
mycell{cell1{cell11{char1, char2}}, char3, cell2{char4, char5, char6}}
i have to get the char variables, and i have to know where they are.
this type of cell is returned, when i do this
get_param(path_to_busselector, 'Inputsignals')
path_to_busselector is the path to a bus selector in Simulink.
I can hard code it, but then i can only handle a fixed number of cell-levels, and this is a problem.
My ideas are, that i construct something with a while loop and probably something with the eval command.
here i have an example model Matlab example model and a skript which gives the signals names. if you run the command signalnames = get_param(BlockPaths(Cellofbusselector)) then there is a cell like i have. now i want to get acces to the signals in the bus selector, but i don't want to do this by hand. If i want to acces the signal in a skript, i have to know the compleete name of the signal. is this clear or am i just unable to tell what i want. sorry if the second statement is true, i will try again
so after i get the name of the signal i can do something like this
set_param(outporthandle_of_busselector, 'Outport', fullsignalname)
and for this i have to know the exact signal name.
Thanks for your time and your ideas
Well I have found a solution. It's not very nice, but it works.
All the files can be downloded here from dropbox
Sorry, I would have liked to post an image, but I don't have 10 reputations. So you have to donwload it from the link above.
Here ist the main skript and further down is a recursif function.
The skript should also work for all other Simulin models with a bus. But just now it just works, if there ist only one busselector. But it is not much to program for several bus systems and bus selectors.
% Name_Signals_after_Blocknames
format compact, clear all, clc
cd(''); % Directory where the simulink model is safed
Simulink_Model = ('linearGuide_model.slx');
Simulink_Model = ('Verbindung.slx');
Simulink_Model = ('bus_system.slx');
% Simulink_Model = ('singlebus.slx');
[path, Model_name, ext] = fileparts(Simulink_Model);
BlockPaths = find_system(Model_name,'LookUnderMasks', 'all' ,'Type','Block');
length_Model_name = length(Model_name);
Cellofbusselector = [];
jj = 0;
for ii = 1:length(BlockPaths)
disp(BlockPaths{ii})
porthandles = get_param(BlockPaths{ii}, 'PortHandles');
outporthandles = get_param(porthandles.Outport, 'Line');
Block_Name = BlockPaths{ii};
% if length(outporthandles) > 1 % only give names to outputs of a subsystem, they are also listed in the BlockPaths cell
% warning ('more than one signal wants to get the same name, might be a Subsystem')
% else
if strcmp(BlockPaths{ii}(end-7:end), 'Selector') % you can not change the name of a line connecting a Bus Selector
disp('Here we have a Bus selector')
jj = 1+jj;
Cellofbusselector(jj) = ii;
else
if isempty(outporthandles)
warning(['Block ', Block_Name, ' has no Output'] )
elseif length(outporthandles) == 1
if outporthandles == -1 % outporthanldes == 1, when there is no signal attachet to the outport of the block
warning(['Block ', Block_Name, ' has no Output-Signal attached'] )
else
Signal_name = BlockPaths{ii}((length_Model_name+2):end);
set_param(outporthandles, 'Name', Signal_name);
end
elseif length(outporthandles) > 1
for jj = 1:length(outporthandles)
if outporthandles{jj} == -1 % outporthanldes == 1, when there is no signal attachet to the outport of the block
Block_Name = BlockPaths{ii};
warning(['Block ', Block_Name, ' has no Output-Signal attached'] )
else
Signal_name = [BlockPaths{ii}((length_Model_name+2):end), '_out', num2str(jj)];
set_param(outporthandles{jj}, 'Name', Signal_name);
end
end
end
end
% end
end % for ii = 1:length(BlockPaths)
buscell = get_param(BlockPaths{Cellofbusselector}, 'InputSignals');
[signalname, buslevel, numofsig, busname] = f_get_complete_signalnames(buscell)
%%
signalnamesize = size(signalname);
for ii = 1:signalnamesize(1)
for kk = 1:signalnamesize(2)
if isempty(signalname{ii,kk})
else
nrofbusnames = kk-1;
fullbusname = '';
for i = 1:nrofbusnames
fullbusname = [fullbusname '.' busname{i}];
end
fullsignames{ii,1} = [fullbusname(2:end) '.' signalname{ii,kk}]
end
end
end
Here is the code from the recursiv function
function [signalname, buslevel, numofsig, busname] = f_get_complete_signalnames(buscell, buslevel, numofsig, signalname, busname)
%% Description
% This function returns the complete signal names which are stored in a
% bus. The name looks something like bus1.bus2.signal1.
if nargin < 2; buslevel = 1; end
if nargin < 3; numofsig = 0; end
if nargin < 4; signalname = {}; end
if nargin < 5; busname = {}; end
buscellsize = size(buscell);
buscellsize(1); % busvert is the vertical dimension of buscell
for kk = 1:buscellsize(1)
if ischar(buscell{kk,1}) && buscellsize(2) == 1
numofsig = numofsig + 1;
signalname{numofsig, buslevel} = buscell{kk,1};
elseif ischar(buscell{kk,1}) && buscellsize(2) == 2
busname{buslevel-1} = buscell{kk,1};
[signalname, buslevel, numofsig, busname] = f_get_complete_signalnames(buscell{kk,2}, buslevel, numofsig, signalname, busname);
elseif iscell(buscell{kk,1}) && buscellsize(2) == 1
buslevel = buslevel+1;
[signalname, buslevel, numofsig, busname] = f_get_complete_signalnames(buscell{kk,1}, buslevel, numofsig, signalname, busname);
buslevel = buslevel-1;
end
end
end
I hope I made this right. And this helps somebody.

Last plot in subplot becomes over-sized

I am using subplot function of MATLAB. Surprisingly the last plot in each subplot set becomes over-sized. Can anybody help me to resolve this issue? I have experimented with the parameters a little, but no luck. I am not able to post the plot figure.
function plotFluxVariabilityByGene(cRxn,KeggID,geneName)
load iJO1366; % Load the model iJO1366
%Find 'Gene' associated reactions from 'model'
reactions = rxnNamesFromKeggID(model,KeggID);
nCheck = 0; % Initialize counter
% Determine initial subplot dimensions
[R C setSize] = subplotSize(numel(reactions));
for n = 1 : numel(reactions)
% Get the name of nth reaction
rxn = reactions{n};
% Define the array for control reaction fluxes
cRxnArray = getCrxnArray(model,cRxn);
% Initialize storage for lower and upper limit-values
L = []; U = []; Avg = [];
% Get the fluxVariability values
for i = 1 : numel(cRxnArray)
modelMod = changeRxnBounds(model,cRxn,cRxnArray(i),'b');
[L(i) U(i)] = fluxVariability(modelMod,100,'max',{rxn});
Avg(i) = (L(i) + U(i))/2;
%fprintf('mthfcFlux = %f; Li = %f; Ui = %f\n',array(i),L(i),U(i));
end
% adjust the subplot number
nCheck = nCheck + 1;
% Determine the range of n to be saved in one file
if nCheck == 1
start = n;
elseif nCheck == setSize;
stop = n;
end
subplot(R,C,nCheck)
plot(cRxnArray,L,'-r','LineWidth',1); hold on;
plot(cRxnArray,L,'^r','MarkerSize',3,'LineWidth',2);
plot(cRxnArray,U,'-.b','LineWidth',1);
plot(cRxnArray,U,'^b','MarkerSize',2,'LineWidth',2);
plot(cRxnArray,Avg,'-','Color',[0.45,0.45,0.45],'LineWidth',2.5);
% Label X and Y axes
%xlabel([cRxn ' Flux']);
%ylabel(['fluxVariability ' char(rxn)]);
xlabel('Flux');
ylabel('fluxVariability');
hold off;
% Adjust X and Y axes limits
%xmn = min(cRxnArray) - ((max(cRxnArray) - min(cRxnArray))*0.05);
%xmx = max(cRxnArray) + ((max(cRxnArray) - min(cRxnArray))*0.05);
%ymn = min([U L]) - ((max([U L]) - min([U L]))*0.05);
%ymx = max([U L]) + ((max([U L]) - min([U L]))*0.05);
%if xmn ~= xmx
% xlim([xmn xmx]);
%end
%if ymn ~= ymx
% ylim([ymn ymx]);
%end
% Print which reactions are done
fprintf('\n......done for %s',char(rxn));
% If 'setSize' subplots are done then save the set in a file
if nCheck == setSize
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.fig']);
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.eps']); close(gcf);
% Determine initial subplot dimensions
[R C setSize] = subplotSize(numel(reactions)-n);
% Return nCheck to zero;
nCheck = 0;
end
end
% If nCheck is not equal to 16 then there are subplot that is not saved
% inside the for loop. Let's save it here.
if nCheck ~= setSize
stop = n;
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.fig']);
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.eps']); close(gcf);
end
fprintf('\nAll done\n');
end
%####################################################
%# Other functions ##
%####################################################
function rxnNames = rxnNamesFromKeggID(model,KeggID)
% Find 'Gene' associated reactions from 'model'
associatedRxns = findRxnsFromGenes(model,KeggID);
% Extract the reaction details from the structure to a cell
rxnDetails = eval(sprintf('associatedRxns.%s',KeggID));
% Extract only the reaction names from the cell
rxnNames = rxnDetails(:,1);
end
%####################################################
function cRxnArray = getCrxnArray(model,cRxn)
% Define the solver
changeCobraSolver('glpk');
% Find solution for the model
sol = optimizeCbModel(model);
% Change the objective of the default model to 'cRxn'
tmpModel = changeObjective(model,cRxn);
% Find slution for the changed model. This gives the maximum and
% minimum possible flux through the reaction 'cRxn' when the model is
% still viable
%solMax = optimizeCbModel(tmpModel,'max');
solMin = optimizeCbModel(tmpModel,'min');
% Create an array of 20 euqally spaced flux values between 'solMin' and
% 'sol.x'
%array = linspace(solMin.f,solMax.f,10);
cRxnArray = linspace(solMin.f,sol.x(findRxnIDs(model,cRxn)),20);
end
%####################################################
function [R C setSize] = subplotSize(remainingPlots)
% Sets number of columns and rows to 3 if total subplot >= 9
if remainingPlots > 7
R = 3; C = 3; setSize = 9;
elseif remainingPlots < 7
R = 2; C = 3; setSize = 6;
elseif remainingPlots < 5
R = 2; C = 2; setSize = 4;
elseif remainingPlots < 4
R = 1; C = 3; setSize = 3;
elseif remainingPlots < 3
R = 1; C = 2; setSize = 2;
end
end
%####################################################
My subplot looks like this:
I suspect its because you are calling subplotSize a second time inside your loop. This could be changing your R and C variables.
I would advise to check the R and C variables at the subplot command on each loop.

Finding the coordinates of a sub-image in an image in Matlab

I need to find the coordinates of a 3D sub-image location residing in a 3D image in Matlab. Can anyone help me?
Thanks,
The following code essentially scans through the large array A and compare each element against the first one in the small array B. If an equal is found, a part of A, of which the size is same as of B, is picked out and compared against B.
clear;clc
% reproduce your scenario
A = randi(100, [30, 20, 10]);
B = A(20:30, 1:18, 4:end);
% counter-case verification
% B(end)=200;
% speed up
lenA = numel(A);
[sa1,sa2,sa3] = size(A);
[sb1,sb2,sb3] = size(B);
% a cumbersome method
eqflag = 0;
counterA = 1;
while (counterA <= lenA)
if A(counterA) == B(1)
[subA1,subA2,subA3] = ind2sub([sa1,sa2,sa3],counterA);
if ( (subA1+sb1-1)<=sa1 ) && ( (subA2+sb2-1)<=sa2 ) ...
&& ( (subA3+sb3-1)<=sa3 ) && isequal( B, ...
A(subA1+(1:sb1)-1,subA2+(1:sb2)-1,subA3+(1:sb3)-1) )
eqflag = 1;
break;
end
end
counterA = counterA + 1;
end
if eqflag
fprintf('found matching starting at A(%d, %d, %d).\n', ...
subA1, subA2, subA3);
fprintf('matching region A(%d:%d, %d:%d, %d:%d).\n', ...
subA1, subA1+sb1-1, subA2, subA2+sb2-1, subA3, subA3+sb3-1);
else
fprintf('no matching found.\n');
end
clearvars sa* lenA counterA
% --------------
% a parallel way
[sa1,sa2,sa3] = size(A);
match_first = find(A==B(1));
[m1,m2,m3] = ind2sub([sa1,sa2,sa3],match_first);
region_first_ind = intersect( intersect(find(m1+sb1-1<=sa1), ...
find(m2+sb2-1<=sa2)),find(m3+sb3-1<=sa3)); % array size issue
region_first = num2cell( [m1(region_first_ind),m2(region_first_ind),...
m3(region_first_ind)], 2);
region = cellfun(#(v) [v;v+[sb1,sb2,sb3]-1], region_first, ...
'UniformOutput', false);
region_match = cellfun(#(v) isequal(A(v(1):v(2), v(3):v(4), v(5):v(6)),...
B), region, 'UniformOutput', false);
match = cell2mat(region([region_match{:}]));
if ~isempty(match)
fprintf('found matching starting at A(%d, %d, %d).\n', ...
match(1), match(3), match(5));
fprintf('matching region A(%d:%d, %d:%d, %d:%d).\n', ...
match(1), match(2), match(3), match(4), match(5), match(6));
else
fprintf('no matching found.\n');
end