I want to find the local maximum and the minimum values between this 2 local maximums in every column of the image img_gauss. And then put them minimum values at 1 (white). Anyone knows how to do this in a easy way?
Below I have my code. But I'm having some trouble, I try in every iteration (for each column) take the localization (locs) and then put them in the array peaks_column, to have the peaks localization by column, but this error apears:
Subscripted assignment dimension mismatch.
Error in cropping_image_long (line 136)
peaks_column(1:size(Intens_graph,1),x)=pks(:,1);
pks= [];
locs_column=zeros(20,size(img_gauss,2));
locs= [];
pks_column=zeros(20,size(img_gauss,2));
for x = 1:size(img_gauss,2) % 2 = colunas x(colunas)
% make a row wise intensity distribution graphic for each column
Intens_graph(:,x)=img_gauss(size(img_gauss,1):-1:1,x);
[pks,locs] = findpeaks(Intens_graph(:,x));%find the local maximum
peaks_column(1:size(Intens_graph,1),x)=pks(:,1); %associate to each column
locs_column(1:size(Intens_graph,1),x)=locs(:,1);
BW = imregionalmin(Intens_graph);
end
Not exactly sure what you mean with the minimums. Between two maximas there will always be one minimum. So i will find minimas with findpeaks.
% test data
data = rand(100);
% for saving minima and maxima positions
minimas = zeros(size(data));
for i = 1:size(data,2)
column = data(:,i);
[~,minis] = findpeaks(-column);
% save the positions
minimas(sub2ind(size(minimas),minis,repmat(i,length(minis),1))) = 1;
end
%generate result, paint all minimas with 1
result = data;
result(minimas==1) = 1;
Related
I am trying to detect high amplitude events and remove them along with rows above and below. I have the following code which does this in part but not fully and I'm not sure where the error is. I have commented out the the audioread function and added randi to allow reproducible results. Code:
%[data, fs] = audioread("noise.wav");
%t1 = linspace(0, (numel(data)-1)/fs, numel(data));
rng(1)
data = randi(10,1000,1);
threshold = 5;
clear_range = 10; %rows/samples
data = clearRange(data, threshold, clear_range);
%t1 = linspace(0, (numel(data)-1)/fs, numel(data));
%plot(t1, data);
plot(data)
function [data] = clearRange(data, threshold, clear_range, compare_column)
% data: matrix of values to clean
% threshold: value to compare values against
% clear_range: number of rows to delete
% compare_column: column to check for value to compare against threshold
if nargin < 4
compare_column = 1;
end
for i = 1:length(data)
if i > length(data)
break
end
if data(i,compare_column) > threshold
data(max(1, i-clear_range):min(length(data), i+clear_range),:) = [];
end
end
end
I think the main problem with your code is that you modify data while looping over it. This means, you delete peaks (or high amplitude events in your words) in rows with an index greater than i, so that they cannot be taken into account in following iterations.
E.g. consider peaks in rows with indices 4 and 6, which should cause that rows up to index 16 are removed (with a value of clear_range equal to 10). However, when i is equal to 4, you remove rows up to index 14. Consequently, you also remove the peak at position 6, so that it is not taken into account in further iterations.
In general, it is easier to rely on MATLAB's matrix/array operations instead of using loops.
Please find below a possible solution with explanations inline.
clc;
% I adjusted inputs to get a minimal example
data = randi(10,30,1);
threshold = 9;
rangeToClear = 1;
columnToCompare = 1;
dataOut = clearRange(data, threshold, rangeToClear, columnToCompare );
disp('In:')
disp( data' );
disp('Out:')
disp( dataOut' ); % Plot for cross-check
function data = clearRange(data, threshold, rangeToClear, columnToCompare)
% rowsWithPeak is 1-D logical array showing where columnToCompare is greater than the threshold
rowsWithPeak = data( :, columnToCompare ) > threshold;
% kernel is a column vector of ones of size Nx1, where N is the number of rows
% that should be removed around a peak
kernel = ones( 2*rangeToClear+1, 1 );
% rowsToRemove is a column vector being greater than one at row indices
% that should be removed from the data. To obtain rowsToRemove,
% we convolute rowsWithPeak with the kernel. The argument 'same' to
% the conv2 function, specifies that rowsToRemove will have the same
% size as rowsWithPeak.
rowsToRemove = conv2( rowsWithPeak, kernel, 'same' );
% rowsToRemoveLogical is a logical array being one, where rowsToRemove is greater than 0.
% Note that, rowsToRemoveLogical = rowsToRemove > 0 would also work here
rowsToRemoveLogical = logical( rowsToRemove);
% Finally, we use rowsToRemoveLogical to mask positions of the rows that should be removed.
data( rowsToRemoveLogical, : ) = [];
end
I need to correct this code it says " Dimension 1 is fixed on the left-hand side but varies on the right ([84480 x 1]..."
I am trying to use the fixedpoint converter to convert this code. However, am having this error of dimenesion 1 is fixed on the left-hand ... for the rxWaveform
rxWaveform = rxWaveform(1+offset:end,:);
function rxWaveform = new_synch(rxWaveform,pssRef)
%PSSIndices = ltePSSIndices(enb); % getting PSS indexes
%pssGrid = lteDLResourceGrid(enb); % generate empty sub frame for PSS symbols
%pssGrid(PSSIndices) = ltePSS(enb); % map PSS symbols into the subframe
%pssRef = lteOFDMModulate(enb,pssGrid); % generate PSS reference signal via LTE OFDM
% getting the lenghts of the received waveform and PSS reference signal
rxSize = size(rxWaveform,1);
pssSize = size(pssRef,1);
% performing correlation between received waveform and pss symbols
pssCorr = xcorr(rxWaveform,pssRef);
% segmenting resultant vector to identify the first local maximum
pssCorr = pssCorr(rxSize - pssSize:rxSize + pssSize,:);
% extract the index of first local maximum, M is not useful here, just for
% the output result
[M,index] = max((abs(pssCorr)));
%calculating offset using local maximum
offset = index - pssSize -1; % subtracted from 1 due to shift in the
rxWaveform = rxWaveform(1+offset:end,:);
end
There are two possible cases here, but the second makes more sense
Case1 : just update a portion of the original array and return the entire arrayrxWaveform
Replace rxWaveform = rxWaveform(1+offset:end,:); by this rxWaveform(1+offset:end,:) = rxWaveform(1+offset:end,:);
rxWaveform size let's say is 90000 by 1
rxWaveform(1+offset:end,:) size is 84480 by 1
Obviously those two dimensions are different
What you're doing is updating a portion of the original rxWaveform
So you need to specify that new portion location as well, that's (1+offset:end,:) on the left side
Case2 : just return a portion of the original array rxWaveform(1+offset:end,:)
If you want to return only just the portion not the entirerxWaveform, just change the function output name, it shouldn't berxWaveform but it can be any variable name, let's say 'output'
The code is as follow
function output = new_synch(rxWaveform,pssRef)
%PSSIndices = ltePSSIndices(enb); % getting PSS indexes
%pssGrid = lteDLResourceGrid(enb); % generate empty sub frame for PSS symbols
%pssGrid(PSSIndices) = ltePSS(enb); % map PSS symbols into the subframe
%pssRef = lteOFDMModulate(enb,pssGrid); % generate PSS reference signal via LTE OFDM
% getting the lenghts of the received waveform and PSS reference signal
rxSize = size(rxWaveform,1);
pssSize = size(pssRef,1);
% performing correlation between received waveform and pss symbols
pssCorr = xcorr(rxWaveform,pssRef);
% segmenting resultant vector to identify the first local maximum
pssCorr = pssCorr(rxSize - pssSize:rxSize + pssSize,:);
% extract the index of first local maximum, M is not useful here, just for
% the output result
[M,index] = max((abs(pssCorr)));
%calculating offset using local maximum
offset = index - pssSize -1; % subtracted from 1 due to shift in the
output = rxWaveform(1+offset:end,:);
end
I'm new to Matlab.
I'm trying to apply PCA function(URL listed below)into my palm print recognition program to generate the eigenpalms. My palm print grey scale images dimension are 450*400.
Before using it, I was trying to study these codes and add some codes to save the eigenvector as .mat file. Some of the %comments added by me for my self understanding.
After a few days of studying, I still unable to get the answers.
I decided to ask for helps.I have a few questions to ask regarding this PCA.m.
PCA.m
What is the input of the "options" should be? of "PCA(data,details,options)"
(is it an integer for reduced dimension? I was trying to figure out where is the "options" value passing, but still unable to get the ans. The msgbox of "h & h2", is to check the codes run until where. I was trying to use integer of 10, but the PCA.m processed dimension are 400*400.)
The "eigvector" that I save as ".mat" file is ready to perform Euclidean distance classifier with other eigenvector? (I'm thinking that eigvector is equal to eigenpalm, like in face recognition, the eigen faces. I was trying to convert the eigenvector matrix back to image, but the image after PCA process is in Black and many dots on it)
mySVD.m
In this function, there are two values that can be changed, which are MAX_MATRIX_SIZE set by 1600 and EIGVECTOR_RATIO set by 0.1%. May I know these values will affect the results? ( I was trying to play around with the values, but I cant see the different. My palm print image dimension is set by 450*400, so the Max_matrix_size should set at 180,000?)
** I hope you guys able to understand what I'm asking, please help, Thanks guys (=
Original Version : http://www.cad.zju.edu.cn/home/dengcai/Data/code/PCA.m
mySVD: http://www.cad.zju.edu.cn/home/dengcai/Data/code/mySVD.m
% Edited Version by me
function [eigvector, eigvalue] = PCA(data,details,options)
%PCA Principal Component Analysis
%
% Usage:
% [eigvector, eigvalue] = PCA(data, options)
% [eigvector, eigvalue] = PCA(data)
%
% Input:
% data - Data matrix. Each row vector of fea is a data point.
% fea = finite element analysis ?????
% options.ReducedDim - The dimensionality of the reduced subspace. If 0,
% all the dimensions will be kept.
% Default is 0.
%
% Output:
% eigvector - Each column is an embedding function, for a new
% data point (row vector) x, y = x*eigvector
% will be the embedding result of x.
% eigvalue - The sorted eigvalue of PCA eigen-problem.
%
% Examples:
% fea = rand(7,10);
% options=[]; %store an empty matrix in options
% options.ReducedDim=4;
% [eigvector,eigvalue] = PCA(fea,4);
% Y = fea*eigvector;
%
% version 3.0 --Dec/2011
% version 2.2 --Feb/2009
% version 2.1 --June/2007
% version 2.0 --May/2007
% version 1.1 --Feb/2006
% version 1.0 --April/2004
%
% Written by Deng Cai (dengcai AT gmail.com)
%
if (~exist('options','var'))
%A = exist('name','kind')
% var = Checks only for variables.
%http://www.mathworks.com/help/matlab/matlab_prog/symbol-reference.html#bsv2dx9-1
%The tilde "~" character is used in comparing arrays for unequal values,
%finding the logical NOT of an array,
%and as a placeholder for an input or output argument you want to omit from a function call.
options = [];
end
h2 = msgbox('not yet');
ReducedDim = 0;
if isfield(options,'ReducedDim')
%tf = isfield(S, 'fieldname')
h2 = msgbox('checked');
ReducedDim = options.ReducedDim;
end
[nSmp,nFea] = size(data);
if (ReducedDim > nFea) || (ReducedDim <=0)
ReducedDim = nFea;
end
if issparse(data)
data = full(data);
end
sampleMean = mean(data,1);
data = (data - repmat(sampleMean,nSmp,1));
[eigvector, eigvalue] = mySVD(data',ReducedDim);
eigvalue = full(diag(eigvalue)).^2;
if isfield(options,'PCARatio')
sumEig = sum(eigvalue);
sumEig = sumEig*options.PCARatio;
sumNow = 0;
for idx = 1:length(eigvalue)
sumNow = sumNow + eigvalue(idx);
if sumNow >= sumEig
break;
end
end
eigvector = eigvector(:,1:idx);
end
%dt get from C# program, user ID and name
evFolder = 'ev\';
userIDName = details; %get ID and Name
userIDNameWE = strcat(userIDName,'\');%get ID and Name with extension
filePath = fullfile('C:\Users\***\Desktop\Data Collection\');
userIDNameFolder = strcat(filePath,userIDNameWE); %ID and Name folder
userIDNameEVFolder = strcat(userIDNameFolder,evFolder);%EV folder in ID and Name Folder
userIDNameEVFile = strcat(userIDNameEVFolder,userIDName); % EV file with ID and Name
if ~exist(userIDNameEVFolder, 'dir')
mkdir(userIDNameEVFolder);
end
newFile = strcat(userIDNameEVFile,'_1');
searchMat = strcat(newFile,'.mat');
if exist(searchMat, 'file')
filePattern = strcat(userIDNameEVFile,'_');
D = dir([userIDNameEVFolder, '*.mat']);
Num = length(D(not([D.isdir])))
Num=Num+1;
fileName = [filePattern,num2str(Num)];
save(fileName,'eigvector');
else
newFile = strcat(userIDNameEVFile,'_1');
save(newFile,'eigvector');
end
You pass options in a structure, for instance:
options.ReducedDim = 2;
or
options.PCARatio =0.4;
The option ReducedDim selects the number of dimensions you want to use to represent the final projection of the original matrix. For instance if you pick option.ReducedDim = 2 you use only the two eigenvectors with largest eigenvalues (the two principal components) to represent your data (in effect the PCA will return the two eigenvectors with largest eigenvalues).
PCARatio instead allows you to pick the number of dimensions as the first eigenvectors with largest eigenvalues that account for fraction PCARatio of the total sum of eigenvalues.
In mySVD.m, I would not increase the default values unless you expect more than 1600 eigenvectors to be necessary to describe your dataset. I think you can safely leave the default values.
I am trying to find the max value and its location. Following is the example of the programme,
fname = dir('*.mat');
nfiles = length(fname);
vals = cell(nfiles,1);
phen = cell(nfiles,1);
for i = 1:nfiles
vals{i} = load(fname(i).name);
phen{i} = (vals{i}.phen);
[M, position] = max(phen{i},[],3);
clear vals
end
After the program is executed, all the position is showing 1. There are total 15 files and M is taking the values of the last file.
How to overcome this prpoblem? Any help will be appreciated
I am not sure I understand your question.
However, at every iteration you are computing the max value and position and overwriting them in the next iteration (i.e. not storing them anywhere). So at the end of the loop M and position would correspond to the last entry phen{nfiles}.
Each time you run through your for loop, you are overwriting M with the max from the most recently loaded phen from the dimension of 3. Since your data is only two dimensional, you probably should be using a dimension of 1 or 2 instead of 3. Because you are using 3, max is returning 1 to position. Fix the dimension issue and position should then be the correct value.
What you could do is make M and position the size of nfiles. So instead of
[M, position] = max(phen{i},[],3);
do
%create M and positions arrays here
%ex. M(nfiles) = 0; or a smaller value if your values are negative
%do the same for positions
[M(i), positions(i)] = max(phen{i},[],1); %1 or 2 correction here here!
then after your for loop
...
end
[maxM, maxMposition] = max(M);
position = positions(maxMposition);
I am on a project thumb recognition system on matlab. I implemented Kmean Algorithm and I got results as well. Actually now I want to plot the results like here they done. I am trying but couldn't be able to do so. I am using the following code.
load training.mat; % loaded just to get trainingData variable
labelData = zeros(200,1);
labelData(1:100,:) = 0;
labelData(101:200,:) = 1;
k=2;
[trainCtr, traina] = kmeans(trainingData,k);
trainingResult1=[];
for i=1:k
trainingResult1 = [trainingResult1 sum(trainCtr(1:100)==i)];
end
trainingResult2=[];
for i=1:k
trainingResult2 = [trainingResult2 sum(trainCtr(101:200)==i)];
end
load testing.mat; % loaded just to get testingData variable
c1 = zeros(k,1054);
c1 = traina;
cluster = zeros(200,1);
for j=1:200
testTemp = repmat(testingData(j,1:1054),k,1);
difference = sum((c1 - testTemp).^2, 2);
[value index] = min(difference);
cluster(j,1) = index;
end
testingResult1 = [];
for i=1:k
testingResult1 = [testingResult1 sum(cluster(1:100)==i)];
end
testingResult2 = [];
for i=1:k
testingResult2 = [testingResult2 sum(cluster(101:200)==i)];
end
in above code trainingData is matrix of 200 X 1054 in which 200 are images of thumbs and 1054 are columns. actually each image is of 25 X 42. I reshaped each image in to row matrix (1 X 1050) and 4 other (some features) columns so total of 1054 columns are in each image. Similarly testingData I made it in the similar manner as I made testingData It is also the order of 200 X 1054. Now my Problem is just to plot the results as they did in here.
After selecting 2 features, you can just follow the example. Start a figure, use hold on, and use plot or scatter to plot the centroids and the data points. E.g.
selectedFeatures = [42,43];
plot(trainingData(trainCtr==1,selectedFeatures(1)),
trainingData(trainCtr==1,selectedFeatures(2)),
'r.','MarkerSize',12)
Would plot the selected feature values of the data points in cluster 1.