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.
Related
% thresholds used for g2NN test
dr2 = 0.5;
extract_feat = 1; % by default extract SIFT features using Hess' code
if(exist('filesift','var') && ~strcmp(filesift,'nofile'))
extract_feat = 0;
end
tic; % to calculate proc time
%C:\python36\Disso\sift-forensic-master
if extract_feat
sift_bin = fullfile('lib','sift','bin','siftfeat'); % e.g. 'lib/sift/bin/siftfeat' in linux
[pf,nf,ef] = fileparts(filename);
desc_file = [fullfile(pf,nf) '.txt'];
im1=imread(filename);
if (size(im1,1)<=1000 && size(im1,2)<=1000)
status1 = system([sift_bin ' -x -o ' desc_file ' ' filename]);
else
status1 = system([sift_bin ' -d -x -o ' desc_file ' ' filename]);
end
if status1 ~=0
error('error calling executables');
end
% import sift descriptors
[num, locs, descs] = import_sift(desc_file);
system(['rm ' desc_file]);
else
% import sift descriptors
[num, locs, descs] = import_sift(filesift);
end
if (num==0)
p1=[];
p2=[];
tp=[];
else
p1=[];
p2=[];
num=0;
% load data
loc1 = locs(:,1:2);
%scale1 = locs(:,3);
%ori1 = locs(:,4);
des1 = descs;
% descriptor are normalized with norm-2
if (size(des1,1)<15000)
des1 = des1./repmat(sqrt(diag(des1*des1')),1,size(des1,2));
else
des1_norm = des1;
for j= 1 : size(des1,2)
des1_j = des1_norm(j,:);
des1_norm(j,:) = des1_j/norm(des1_j,2);
end
des1 = des1_norm;
end
% sift matching
des2t = des1'; % precompute matrix transpose
if size(des1,1) > 1 % start the matching procedure iff there are at least 2 points
for i = 1 : size(des1,1)
dotprods = des1(i,:) * des2t; % Computes vector of dot products
[vals,indx] = sort(acos(dotprods)); % Take inverse cosine and sort results
j=2;
while vals(j)<dr2* vals(j+1)
j=j+1;
end
for k = 2 : j-1
match(i) = indx(k);
if pdist([loc1(i,1) loc1(i,2); loc1(match(i),1) loc1(match(i),2)]) >10
p1 = [p1 [loc1(i,2); loc1(i,1); 1]];
p2 = [p2 [loc1(match(i),2); loc1(match(i),1); 1]];
num=num+1;
end
end
end
end
tp = toc; % processing time (features + matching)
if size(p1,1)==0
fprintf('Found %d matches.\n', num);
else
p=[p1(1:2,:)' p2(1:2,:)'];
p=unique(p,'rows');
p1=[p(:,1:2)'; ones(1,size(p,1))];
p2=[p(:,3:4)'; ones(1,size(p,1))];
num=size(p1,2);
fprintf('Found %d matches.\n', num);
end
end
Hi all,
I have uploaded the code above for copy-move forgery detection. While running the code there are several errors which I am getting. I have also uploaded the snippet of the error that I am having trouble to fix with. I have also contacted the guy who wrote this code and he replied to me with following message: "You need to compile the third party library in the folder bin/sift accordingly to your operative system.".
I hope to find the solution here.
A snippet of the error
i write a code using GUI and Mfile in MATHLAB. in my program i have a board.each time, computer put a marble and rotate the board then get a marble place and rotate direction of the board from user and After each of these things, i want it shows the result in axes1 in GUI. but it doesen't work in line 9 in the code below:
% some codes...
1. while(currentDepth < 7)
2. if(mod(currentDepth,2) ~= (plrC-1))
3. plat(currentDepth);
4. drawTable(); % show the result in axes1 --> it works
5. else
6. getMarble();
7. drawTable(); % show the result in axes1 --> it works
8. rotate();
9. drawTable(); % show the result in axes1 --> it dosen't work
10. end
11. end
% some codes...
.
function drawTable()
global board;
% some codes...
imshow(board,[0 4]);
end
do you have any idea?
it's rotate function. th board is divided into 4 parts just 1 part rotates.
function rotate()
global board;
block = 0;
vector = 'non';
while(block<1 || block>4)
block = str2double(cell2mat(inputdlg('chose a block: 1/2/3/4','board rotation')));
end
switch block
case 1
k=1; z=1;
case 2
k=1; z=4;
case 3
k=4; z=1;
case 4
k=4; z=4;
end
while(~strcmp(vector,'left') && ~strcmp(vector,'right'))
vector = questdlg('rotate left or right','Rotation','left','right','right');
end
if(strcmp(vector,'left'))
board(k:k+2,z:z+2)=rot90(board(k:k+2,z:z+2));
else
board(k:k+2,z:z+2)=rot90(board(k:k+2,z:z+2),3);
end
end
ok now here we have a simplified code. make a new GUI with an axes then run the code below from 'OpeningFnc'. you will see my problem.
function test()
currentDepth = 1;
plrC = 1;
plrO = 2;
board = zeros(6);
while(currentDepth < 40)
if(mod(currentDepth,2) == 1)
plat();
drawTable(); % show the result in axes1 --> it works
else
getMarble();
drawTable(); % show the result in axes1 --> it works
rotate();
drawTable(); % show the result in axes1 --> it dosen't work
end
currentDepth = currentDepth +1;
end
function plat()
for a=1:5000
for b=1:5000
for c=1:50
m = a + b;
end
end
end
row = 1;
column = 1;
while(board(row,column) ~= 0)
row = randi(6);
column = randi(6);
end
board(row,column) = plrC;
row = randi([1 4]);
column = randi([1 4]);
board(row:row+2,column:column+2)=rot90(board(row:row+2,column:column+2));
end
function drawTable()
board(board==0) = board(board==0)+4;
B = zeros(305);
B(:,152:154) = 3;
B(152:154,:) = 3;
for i=1:6
for j=1:6
x = (i*5)+1+(i-1)*45;
y = (j*5)+1+(j-1)*45;
B(x:x+44,y:y+44) = board(i,j);
end
end
imshow(B,[0 4]);
board(board==4) = board(board==4)*0;
end
function getMarble()
board(board==0) = board(board==0)+4;
b = zeros(305);
b(:,152:154) = 3;
b(152:154,:) = 3;
for i=1:6
for j=1:6
x = (i*5)+1+(i-1)*45;
y = (j*5)+1+(j-1)*45;
b(x:x+44,y:y+44) = board(i,j);
end
end
imshow(b,[0 4]);
i = 0;
while(i~=4)
[x,y] = ginput(1);
if(x<0 || x>305 || y<0 || y>305)
i = 0;
else
i = b(ceil(y),ceil(x));
end
end
y = ceil(y/50);
x = ceil(x/50);
board(y,x) = plrO;
end
function rotate()
block = 0;
vector = 'non';
while(block<1 || block>4)
block = str2double(cell2mat(inputdlg('chose a block: 1/2/3/4','board rotation')));
end
switch block
case 1
k=1; z=1;
case 2
k=1; z=4;
case 3
k=4; z=1;
case 4
k=4; z=4;
end
while(~strcmp(vector,'left') && ~strcmp(vector,'right'))
vector = questdlg('rotate left or right','Rotation','left','right','right');
end
if(strcmp(vector,'left'))
board(k:k+2,z:z+2)=rot90(board(k:k+2,z:z+2));
else
board(k:k+2,z:z+2)=rot90(board(k:k+2,z:z+2),3);
end
end
end
as ThP said, i have to add drawnow() function at the end of drawTable.
At my wit's end. This program used to work for me, but now for some reason I keep getting that I cannot open the file. (Was using the same file before and no problem). I tried to just switch to wavread only and it worked but it added all sorts of complications for me to debug throughout the rest of my program, so I'd really like to get wav_to_audio working again.
The error message is
Error using wavread (line 70) Invalid Wave File. Reason: Cannot open file.
Error in wav_to_audio (line 108) [f_audio,fs,nbits] = wavread(strcat(dirAbs,dirRel,wavfilename));
Error in test_TempogramToolbox (line 61) [audio,sideinfo] = wav_to_audio('',dirWav,filename);
Here is the matlab code:
clear close all
dirWav = 'data_wav/';
filename = 'Debussy_SonataViolinPianoGMinor-02_111_20080519-SMD-ss135-189.wav';
% filename = '110-130bpm_click.wav';
% filename = 'Faure_Op015-01_126_20100612-SMD-0-12.wav';
% filename = 'Poulenc_Valse_114_20100518-SMD-0-15.wav';
% filename = 'Schumann_Op015-03_113_20080115-SMD-0-13.wav';
%% load wav file, automatically converted to Fs = 22050 and mono
[audio,sideinfo] = wav_to_audio('',dirWav,filename); Fs = sideinfo.wav.fs;
%% wav_to_audio function
if parameter.message == 1
fprintf('wav_to_audio: processing %s, ',wavfilename);
end
[pathstr,name,ext] = fileparts(wavfilename);
if strcmp(ext,'.wav')
[f_audio,fs,nbits] = wavread(strcat(dirAbs,dirRel,wavfilename));
else
error(['Unknown file format ' ext]);
end
bConverted_to_mono = 0;
if parameter.convertToMono
if size(f_audio,2)>1
bConverted_to_mono = 1;
if parameter.message == 1
fprintf('converting to mono, ');
end
switch parameter.monoConvertMode
case 'leftmost_channel'
f_audio= f_audio(:,1);
case 'rightmost_channel'
f_audio= f_audio(:,size(f_audio,2));
case 'downmix' % pay attention to energy loss due to differences in phase
% when using this method. This is often the case for bad
% stereo mixes
nChannels = size(f_audio,2);
f_audio = sum(f_audio,2);
f_audio = f_audio / nChannels;
otherwise
disp('wav_to_audio: monoConvertMode : Unknown method')
end
end
end
bResampled = 0;
if parameter.useResampling
if (fs ~= parameter.destSamplerate)
bResampled = 1;
if parameter.message == 1
fprintf('Resampling to %d, ', parameter.destSamplerate);
end
f_audio = resample (f_audio,parameter.destSamplerate,fs,100);
fs = parameter.destSamplerate;
end
end
%% Update sideinfo
sideinfo.wav.version = 1;
sideinfo.wav.filename = wavfilename;
sideinfo.wav.dirRel = dirRel;
sideinfo.wav.size = size(f_audio,1);
sideinfo.wav.duration = (sideinfo.wav.size-1)/fs;
sideinfo.wav.energy = sum(f_audio.^2);
sideinfo.wav.fs = fs;
sideinfo.wav.nbits = nbits;
sideinfo.wav.channels = size(f_audio,2);
sideinfo.wav.resampled = bResampled;
sideinfo.wav.monoConverted = bConverted_to_mono;
if bConverted_to_mono
sideinfo.wav.monoConvertMode = parameter.monoConvertMode;
else
sideinfo.wav.monoConvertMode = 'none';
end
%% Saving data
if parameter.save == 1
if parameter.message == 1
fprintf('Saving to file, ');
end
filename = strcat(parameter.saveFilename,'_audio');
save(strcat(parameter.saveDir,filename),'f_audio','sideinfo');
end
if parameter.message == 1
fprintf('Done\n');
end
%% Visualization
if parameter.vis
figure;
for k=1:sideinfo.wav.channels
if sideinfo.wav.channels > 1
subplot(sideinfo.wav.channels,1,k);
end
plot( [0:sideinfo.wav.size-1] / sideinfo.wav.fs , f_audio(:,k));
axis tight;
end
end
end
I want to overlay my line plot in Matlab with colored bars for different x-axis values. The functionality I'm looking for is much like recessionplot(), but it should not indicate NBER recessions, but user defined periods. I'm able to do this with the following code, but the color of my original line is changed. How do I avoid this in the best way?
%%%%%%%%%%%% Functions to shade %%%%%%%%%%%%%%%%%%%
function []=shadedates(Start,Finish,colorstr)
curax=axis;
indx1=find(Finish>curax(1)); % First Date to include;
indx2=find(Start<curax(2)); % Last Date to include;
indx1=indx1(1);
indx2=indx2(length(indx2));
if Start(indx1)<curax(1);
Start(indx1)=curax(1);
end;
if Finish(indx2)>curax(2);
Finish(indx2)=curax(2);
end;
shade(Start(indx1:indx2),Finish(indx1:indx2),colorstr);
end
function []=shade(Start,Finish,colorstr)
% Start and Finish are Nx1 vectors of starting and ending years.
% The function shades between the start and finish pairs using colorstr
if ~exist('colorstr','var'); colorstr='y'; end; % default is yellow
curax=axis;
y=[curax(3) curax(4) curax(4) curax(3)];
hold on;
for i=1:length(Start);
x=[Start(i) Start(i) Finish(i) Finish(i)];
h=fill(x,y,colorstr);
set(h,'facealpha',.3)
end;
h = findobj(gca,'Type','patch');
set(h,'EdgeColor','none');
% This last one makes the tick marks visible
set(gca, 'Layer', 'top')
end
%%%%%%%%%%%%%%% Create data %%%%%%%%%%%%%%%%%%%%%%
GLI.Dates = transpose(714890:(714890+99));
GLI.GLI = cumsum([50;normrnd(0,1,99,1)]);
GLI.ProsStart = zeros(size(GLI.GLI));
GLI.RecStart = zeros(size(GLI.GLI));
GLI.ProsFin = zeros(size(GLI.GLI));
GLI.RecFin = zeros(size(GLI.GLI));
TempLag = GLI.GLI(1);
CurPhase = 0;
for i=2:size(GLI.GLI,1)
Temp = GLI.GLI(i);
if Temp > TempLag && CurPhase ~= 1
GLI.ProsStart(i-1) = 1;
if CurPhase == 2
GLI.RecFin(i-1) = 1;
end
CurPhase = 1;
elseif Temp < TempLag && CurPhase ~= 2
GLI.RecStart(i-1) = 1;
if CurPhase == 1
GLI.ProsFin(i-1) = 1;
end
CurPhase = 2;
end
TempLag = Temp;
end
if CurPhase == 1
GLI.ProsFin(end) = 1;
elseif CurPhase == 2
GLI.RecFin(end) = 1;
end
%%%%%%%%%%%%%%%%%%% Create plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plot(GLI.Dates,GLI.GLI)
colorstr=[0 1 0];
shadedates(GLI.Dates(logical(GLI.ProsStart)),GLI.Dates(logical(GLI.ProsFin)),colorstr)
colorstr=[1 0 0];
shadedates(GLI.Dates(logical(GLI.RecStart)),GLI.Dates(logical(GLI.RecFin)),colorstr)
save a handle to the plotted object:
p = plot(GLI.Dates,GLI.GLI)
and then use this (after the calls to shadedates):
uistack(p,'top')
(I have this from here)
I have implemented the Clarke-Wright huristic to solve TSP (based on the pseudo-code here). I have attached my implementation in Matlab. However it is not fast enough for me and takes O(n2) space (because of pairwise distances). I wonder if there is any theoretic or practical optimization I can apply to reduce the complexity (specially, space complexity).
It would be grateful if anyone can help me.
function [tour, length] = clarke_wright (data)
n=size(data,1); % number of records
center = mean(data,1); % mean of data
hubIdx = knnsearch(data,center,'k',1); % nearest record to center
distances = dist(data,data'); % this requires O(n^2) space :(
savings = zeros(n); % place to store the saving after adding an edge %
% Can be more vectorized? %
for i=1:n
if i==hubIdx
continue;
end
savings(i,(i+1):n)=distances(i,hubIdx)+distances(hubIdx,(i+1):n)-distances(i,(i+1):n);
end
minParent = 1:n;
[~,si] = sort(savings(:),'descend');
si=si(1:(end/2));
Vh = zeros(1,n);
Vh(hubIdx) = 1;
VhCount = n-1;
degrees = zeros(1,n);
selectedIdx = 1; % edge to try for insertion
tour = zeros(n,2);
curEdgeCount = 1;
while VhCount>2
i = mod(si(selectedIdx)-1,n)+1;
j = floor((si(selectedIdx)-1)/n)+1;
if Vh(i)==0 && Vh(j)==0 && (minParent(i)~=minParent(j)) && i~=j && i~=hubIdx && j~=hubIdx % always all degrees are <= 2, so it is not required to check them
% if (minParent(i)~=minParent(j)) && isempty(find(degrees>2, 1)) && i~=j && i~=hubIdx && j~=hubIdx && Vh(i)==0 && Vh(j)==0
degrees(i)=degrees(i)+1;
degrees(j)=degrees(j)+1;
tour(curEdgeCount,:) = [i,j];
if minParent(i)<minParent(j)
minParent(minParent==minParent(j))=minParent(i);
else
minParent(minParent==minParent(i))=minParent(j);
end
curEdgeCount = curEdgeCount + 1;
if degrees(i)==2
Vh(i) = 1;
VhCount = VhCount - 1;
end
if degrees(j)==2
Vh(j) = 1;
VhCount = VhCount - 1;
end
end
selectedIdx = selectedIdx + 1;
end
remain = find(Vh==0);
n1=remain(1);
n2=remain(2);
tour(curEdgeCount,:) = [hubIdx n1];
curEdgeCount = curEdgeCount + 1;
tour(curEdgeCount,:) = [hubIdx n2];
tour = stitchTour(tour);
tour=tour(:,1)';
length=distances(tour(end),tour(1));
for i=1:n-1 % how can I vectorize these lines?
length=length+distances(tour(i),tour(i+1));
end
end
function tour = stitchTour(t) % uniforms the tour [a b; b c; c d; d e;.... ]
n=size(t,1);
[~,nIdx] = sort(t(:,1));
t=t(nIdx,:);
tour(1,:) = t(1,:);
t(1,:) = -t(1,:);
lastNodeIdx = tour(1,2);
for i=2:n
nextEdgeIdx = find(t(:,1)==lastNodeIdx,1);
if ~isempty(nextEdgeIdx)
tour(i,:) = t(nextEdgeIdx,:);
t(nextEdgeIdx,:)=-t(nextEdgeIdx,:);
else
nextEdgeIdx = find(t(:,2)==lastNodeIdx,1);
tour(i,:) = t(nextEdgeIdx,[2 1]);
t(nextEdgeIdx,:)=-t(nextEdgeIdx,:);
end
lastNodeIdx = tour(i,2);
end
end
This is what you can do if space is an issue (will probably reduce calculation speed a bit).
I have not really looked into your code, but judging from the pseudo code this should do the trick:
For each pair or points, calculate the savings created by connecting them.
If this is better than the best savings found so far, update the best savings, and remember the two points.
After checking all pairs just implement the best savings.
This way you will barely require extra space at all.