I need help plotting different permutations of an if/else command in different colors on the same plot - matlab

Basically I have a code where it produces a plot of all possible permutations between Cost and Reliability. There's a total of 864 data points split up between 8 rows. Five of the rows have 2 options and three of them 3 options.
Given here is a copy of my code. I'm trying to have the permutations of 'Other Cameras' and 'Depth & Structure Testing' have a different color with the other six possibilities. I tried using the 'gscatter' command but didn't have much luck with it.
I believe I need to have the scatter command in the if/else statements themselves, although I'm not too sure what to plot in the 'X' and 'Y' for the 'scatter' command. Currently my code is set up for plotting all the data in one color. I deleted my code with the 'gscatter' because I got many errors and when I tried to fix them the plot ultimately didn't work as planned.
% Pareto_Eval
baseline_cost = 45;
nrows = 8;
%Initialize Variables
for aa = 1:nrows
cost_delta(aa) = 0;
reliability(aa) = 1;
end
icount = 1;
%Propulsion
for row1 = 1:2
if row1 == 1
cost_delta(1)= -7;
reliability(1) = 0.995;
elseif row1==2
cost_delta(1)=0;
reliability(1)=.99;
end
%Entry Mode
for row2 = 1:2
if row2 == 1
cost_delta(2) = -3;
reliability(2) = .99;
else
cost_delta(2) = 0;
reliability(2) = .98;
end
%Landing Method
for row3 = 1:3
if row3 == 1 %if needs declaration
cost_delta(3)= 0;
reliability(3) = .99;
elseif row3 == 2 %elseif needs declaration
cost_delta(3) = 4;
reliability(3) = .995;
else %else does not need declaration
cost_delta(3) = -2;
reliability(3) = .95;
end
%Lander Type
for row4 = 1:3
if row4 == 1
cost_delta(4)= 10;
reliability(4) = .99;
elseif row4 == 2
cost_delta(4) = 0;
reliability(4) = .99;
else
cost_delta(4) = 15;
reliability(4) = .95;
end
%Rover Type
for row5 = 1:2
if row5 == 1
cost_delta(5)= -2;
reliability(5) = .98;
else
cost_delta(5) = 0;
reliability(5) = .975;
end
%Power Source
for row6 = 1:2
if row6 == 1
cost_delta(6) = -3;
reliability(6) = .95;
else
cost_delta(6) = 0;
reliability(6) = .995;
end
%Depth & Structure Testing
for row7 = 1:2
if row7 == 1
cost_delta(7) = 0;
reliability(7) = .99;
else
cost_delta(7) = 2;
reliability(7) = .85;
end
%Other Cameras
for row8 = 1:3
if row8 == 1
cost_delta(8)= -1;
reliability(8) = .99;
elseif row8 == 2
cost_delta(8) = -1;
reliability(8) = .99;
else
cost_delta(8) = 0;
reliability(8) = .9801;
end
cost_delta_total = 0;
reliability_product = 1;
for bb=1:nrows
cost_delta_total = cost_delta_total + cost_delta(bb);
reliability_product = reliability_product*reliability(bb);
end
total_cost(icount) = baseline_cost + cost_delta_total;
total_reliability(icount) = reliability_product;
icount = icount + 1;
end; end; end; %Rows 1,2,3
end; end; end; %Rows 4,5,6
end; end; %Rows 7,8
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(total_reliability, total_cost, sz, 'blue')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
Any help is appreciated. I don't have a lot of experience with Matlab and I've tried looking around for help but nothing really worked.
Here is a sample code to make questions easier I created:
% Pareto_Eval
baseline_cost = 55;
nrows = 3;
%Initialize Variables
for aa = 1:nrows
cost_delta(aa) = 0;
reliability(aa) = 1;
end
icount = 1;
%Group 1
for row1 = 1:2
if row1 == 1
cost_delta(1)= 5;
reliability(1) = 0.999;
elseif row1==2
cost_delta(1) = 0;
reliability(1) = .995;
end
%Group 2
for row2 = 1:2
if row2 == 1
cost_delta(2) = 0;
reliability(2) = .98;
else
cost_delta(2) = -2;
reliability(2) = .95;
end
%Group 3
for row3 = 1:2
if row3 == 1
cost_delta(3) = 3;
reliability(3) = .997;
else
cost_delta(3) = 0;
reliability(3) = .96;
end
%initializing each row
cost_delta_total = 0;
reliability_product = 1;
for bb = 1:nrows
cost_delta_total = cost_delta_total + cost_delta(bb);
reliability_product = reliability_product*reliability(bb);
end
total_cost(icount) = baseline_cost + cost_delta_total;
total_reliability(icount) = reliability_product;
icount = icount + 1;
end
end
end
fignum=1;
figure(fignum)
sz = 25;
scatter(total_reliability, total_cost, sz)
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
Basically I need to make a plot in each if-loop, but I'm not sure how to do it and have them all on the same plot

sounds like an interesting project! Not sure if I understood your intended plots correctly, but hopefully the code below gets you a bit closer to what you are looking for.
I've started off with a rather deep mess of nested for loops (as you did) but kept it more concise bybuilding a permutations matrix.
counter = 0;
for propulsion_options = 1:2
for entry_mode = 1:2
for landing_method = 1:3
for lander_type = 1:3
for rover_type = 1:2
for power_source = 1:2
for depth_testing = 1:2
for other_cameras = 1:3
counter = counter +1
permutations(counter,:) = [...
propulsion_options,...
entry_mode,...
landing_method,...
lander_type,...
rover_type,...
power_source,...
depth_testing,...
other_cameras];
end
end
end
end
end
end
end
end
This way I kept the actual scoring out of the loops, and perhaps easier to tweak the values. I initialised the cost and reliabiltiy arrays to be the same size as the permutations array:
cost_delta = zeros(size(permutations));
reliability = zeros(size(permutations));
Then for each metric, I searched the permutations array for all occurances of each possible value and assigned the appropriate score:
%propulsion
propertyNo = 1;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -7;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
%entry_mode (2)
propertyNo = 2;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.98;
%landing_method (3)
propertyNo = 3;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 4;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = -2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;
%lander_type (3)
propertyNo = 4;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 10;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 15;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;
%rover_type (2)
propertyNo = 5;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -2;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.98;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.975;
%power_source (2)
propertyNo = 6;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.95;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
%depth_testing (2)
propertyNo = 7;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.85;
%other_cameras (3)
propertyNo = 8;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.9801;
Then each permutation can have a total cost / reliabiltiy score by summing and takign the product along the second dimension:
cost_delta_total = sum(cost_delta,2);
reliability_product = prod(reliability,2);
Finally, you can plot all points (as per your original):
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(reliability_product, cost_delta_total, sz, 'b')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
or you can create an index into the permutations by searching for specific property values and plot these different colours (actually this bit answers your most specific question of how to plot two things on the same axes - you just need the hold on; command):
propertyNo = 7;
indexDepth1 = find(permutations(:,propertyNo)==1);
indexDepth2 = find(permutations(:,propertyNo)==2);
fignum=2;
figure(fignum)
sz = 5;
scatter(reliability_product(indexDepth1), cost_delta_total(indexDepth1), sz, 'k');
hold on;
scatter(reliability_product(indexDepth2), cost_delta_total(indexDepth2), sz, 'b');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Depth & Structure Test 1','Depth & Structure Test 2')
propertyNo = 8;
indexCam1 = find(permutations(:,propertyNo)==1);
indexCam2 = find(permutations(:,propertyNo)==2);
indexCam3 = find(permutations(:,propertyNo)==3);
fignum=3;
figure(fignum)
sz = 5;
scatter(reliability_product(indexCam1), cost_delta_total(indexCam1), sz, 'k');
hold on;
scatter(reliability_product(indexCam2), cost_delta_total(indexCam2), sz, 'b');
scatter(reliability_product(indexCam3), cost_delta_total(indexCam3), sz, 'g');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Other Camera 1','Other Camera 2','Other Camera 3')
Good luck with the mission! When is launch day?

Related

MATLAB 'parfor' Loops Very Slow When Compared With 'for' loop

I have a script that I'm running, and at one point I have a loop over n objects, where I want n to be fairly large.
I have access to a server, so I put in a parfor loop. However, this is incredibly slow compared with a standard for loops.
For example, running a certain configuration ( the one below ) with the parfor loop on 35 workers took 68 seconds, whereas the for loop took 2.3 seconds.
I know there's stuff to do with array-broadcasting that can cause issues, but I don't know a lot about this.
n = 20;
r = 1/30;
tic
X = rand([2,n-1]);
X = [X,[0.5;0.5]];
D = sq_distance(X,X);
A = sparse((D < r) - eye(n));
% Infected set I
I = n;
[S,C] = graphconncomp(A);
compnum = C(I);
I_new = find(C == compnum);
I = I_new;
figure%('visible','off')
gplot(A,X')
hold on
plot(X(1,I),X(2,I),'r.')
hold off
title('time = 0')
axis([0,1,0,1])
time = 0;
t_max = 10; t_int = 1/100;
TIME = 1; T_plot = t_int^(-1) /100;
loops = t_max / T_plot;
F(loops) = struct('cdata',[],'colormap',[]);
F(1) = getframe;
% Probability of healing in interval of length t_int
heal_rate = 1/3; % (higher number is faster heal)
p_heal = t_int * heal_rate;
numhealed = 0;
while time < t_max
time = time+t_int;
steps = poissrnd(t_int,[n,1]);
parfor k = 1:n
for s = 1:steps(k)
unit_vec = unif_unitvector;
X_new = X(:,k) + unit_vec*t_int;
if ( X_new < 1 == ones(2,1) ) ...
& ( X_new > 0 == ones(2,1) )
X(:,k) = X_new;
end
end
end
D = sq_distance(X,X);
A = sparse((D < r) - eye(n));
[S,C] = graphconncomp(A);
particles_healed = binornd(ones(length(I),1),p_heal);
still_infected = find(particles_healed == 0);
I = I(still_infected);
numhealed = numhealed + sum(particles_healed);
I_new = I;
% compnum = zeros(length(I),1);
for i = 1:length(I)
compnum = C(I(i));
I_new = union(I_new,find(C == compnum));
end
I = I_new;
if time >= T_plot*TIME
gplot(A,X')
hold on
plot(X(1,I),X(2,I),'r.')
hold off
title(sprintf('time = %1g',time))
axis([0,1,0,1])
% fprintf('number healed = %1g\n',numhealed)
numhealed = 0;
F(TIME) = getframe;
TIME = TIME + 1;
end
end
toc

Matlab: iterate through image blocks

I would like to divide an image into 8 by 6 blocks and then from each block would like to get the average of red, green and blue values then store the average values from each block into an array. Say that if I have image divided into 4 blocks the result array would be:
A = [average_red, average_green, average_blue,average_red, ...
average_green, average_blue,average_red, average_green, ...
average_blue,average_red, average_green, average_blue,...
average_red, average_green, average_blue,]
The loop I have created looks very complicated, takes a long time to run and I'm not even sure if it's working properly or not as I have no clue how to check. Is there any simpler way to implement this.
Here is the loop:
[rows, columns, ~] = size(img);
[rows, columns, ~] = size(img);
rBlock = 6;
cBlock = 8;
NumberOfBlocks = rBlock * cBlock;
bRow = ceil(rows/rBlock);
bCol = ceil(columns/cBlock);
row = bRow;
col = bCol;
r = zeros(row*col,1);
g = zeros(row*col,1);
b = zeros(row*col,1);
n = 1;
cl = 1;
rw = 1;
for x = 1:NumberOfBlocks
for i = cl : col
for j = rw : row
% some code
end
end
%some code
if i == columns && j ~= rows
cl = 1;
rw = j - (bRow -1);
col = (col - col) + bCol;
row = row + bRaw;
elseif a == columns && c == rows
display('done');
else
cl = i + 1;
rw = j - (bRow -1);
col = col + col;
row = row + row;
end
end
Because there are only 48 block, you may use simple for loop iterating blocks. (I think it's going to be fast enough).
Here is my code:
%Build test image
img = double(imresize(imread('peppers.png'), [200, 300]));
[rows, columns, ~] = size(img);
rBlock = 6;
cBlock = 8;
NumberOfBlocks = rBlock * cBlock;
bRow = ceil(rows/rBlock);
bCol = ceil(columns/cBlock);
idx = 1;
A = zeros(1, rBlock*cBlock*3);
for y = 0:rBlock-1
for x = 0:cBlock-1
%Block (y,x) boundaries: (x0,y0) to (x1,y1)
x0 = x*bCol+1;
y0 = y*bRow+1;
x1 = min(x0+bCol-1, columns); %Limit x1 to columns
y1 = min(y0+bRow-1, rows); %Limit y1 to rows
redMean = mean2(img(y0:y1, x0:x1, 1)); %Mean of red pixel in block (y,x)
greenMean = mean2(img(y0:y1, x0:x1, 2)); %Mean of green pixel in block (y,x)
blueMean = mean2(img(y0:y1, x0:x1, 3)); %Mean of blue pixel in block (y,x)
%Fill 3 elements of array A.
A(idx) = redMean;
A(idx+1) = greenMean;
A(idx+2) = blueMean;
%Advance index by 3.
idx = idx + 3;
end
end

Neural network input mistmatch (Iris Dataset)

I currently have an error that i can't pass this is the short code and everything needed in order to have a general idea about my problem
clear;
close all; clear ;
load fisheriris;
m = meas;
d = num2cell(m);
d(:,5) = species(:,1);
c = cvpartition(d(:,5),'kfold',10);
CeDam = cell(10,1);
CeVrem = cell(10,1);
for i=1:10
CeDam{i} = [d(test(c,i),1) d(test(c,i),2) d(test(c,i),3) d(test(c,i),4)]';
end
for i=1:10
CeVrem{i} = d(test(c,i),5)';
end
for i = 1:10
a = CeVrem{i};
[n,m] = size(a);
for j = 1:n
for k = 1:m
if isequal(a(j,k),'setosa') a{n,m} = [1 0 0];
elseif isequal(a(j,k),'versicolor') a{n,m} = [0 1 0];
else a{j,k} = [0,0,1];
end
end
end
CeVrem{i} = a;
end
net = newff(cell2mat(minmax(CeDam{1})),[3 3 3],{'logsig','logsig','logsig',},'trainlm');
net.LW{2,1} = net.LW{2,1}*0.5;
net.b{2} = net.b{2}*2;
net.performFcn = 'mse';
net.trainParam.epochs = 100;
err = 0;
i = 1;
j = 1;
while i <= 10
while j <= 10
if i~=j net = train(net,CeDam{j},CeVrem{j});
end
j=j+1;
end
end
in the train part of the algorithm it gives me an input mistmatch which is very odd for me.
The error messages:
Error using trainlm (line 109) Number of inputs does not match
net.numInputs.
Error in network/train (line 106) [net,tr] =
feval(net.trainFcn,net,X,T,Xi,Ai,EW,net.trainParam);
i managed to fix everything after much work here is the code that works for anyone having the same problem in the future gl :D :).
clear;
close all; clear ;
load fisheriris;
m = meas;
d = num2cell(m);
d(:,5) = species(:,1);
c = cvpartition(d(:,5),'kfold',10);
CeDam = cell(10,1);
CeVrem = cell(10,1);
for i=1:10
CeDam{i} = [m(test(c,i),1) m(test(c,i),2) m(test(c,i),3) m(test(c,i),4)]';
end
for i=1:10
CeVrem{i} = d(test(c,i),5);
end
for i = 1:10
a = CeVrem{i}';
[n,m] = size(a);
b = zeros(3,m);
for j = 1:n
for k = 1:m
if isequal(a(j,k),{'setosa'}) b(1,k) = 1; b(2,k) = 0; b(3,k) = 0;
elseif isequal(a(j,k),{'versicolor'}) b(1,k) = 0; b(2,k) = 1; b(3,k) = 0;
else b(1,k) = 0; b(2,k) = 0; b(3,k) = 1;
end
end
end
CC{i} = b;
end
CC = CC';
net = newff(minmax(CeDam{1}),[3 3 3],{'logsig','logsig','logsig'},'trainlm');
net.LW{2,1} = net.LW{2,1}*0.6;
net.b{2} = net.b{2}*2;
net.performFcn = 'mse';
net.trainParam.epochs = 100;
errglob = 0;
i = 1;
j = 1;
while i <= 10
while j <= 10
if i~=j net = train(net,CeDam{j},CC{j});
end
j=j+1;
end
y=sim(net,CeDam{i});
y=round(y);
e = y - CC{i};
errcur=mse(net,CC{i},y);
errglob = errglob + mse(net,CC{i},y);
fprintf('Avem o eroare de %.2f pe foldul %d \n',errcur,i)
i=i+1;
end
errglob/10
this thread can be closed thx :)
I think you got some problems with mixing up cell and array formats...
Try to replace:
net = train(net,CeDam{j},CeVrem{j});
by:
net = train(net,cell2mat(CeDam{j}),cell2mat(CeVrem{j}')');
AND: please remove your infinite loops in i, by adding i=i+1; or replace the while loops by more natural for loops, e.g.
for i = 1:10
for j = 1:10
if i~=j
net = train(net,cell2mat(CeDam{j}),cell2mat(CeVrem{j}')');
end
end
end
AND: Where are you using your i inside the loop? I guess something is missing there...

Filter points using hist in matlab

I have a vector. I want to remove outliers. I got bin and no of values in that bin. I want to remove all points based on the number of elements in each bin.
Data:
d1 =[
360.471912914169
505.084636471948
514.39429429184
505.285068055647
536.321181755858
503.025854206322
534.304229816684
393.387035881967
396.497969729985
520.592172434431
421.284713703215
420.401106087984
537.05330275495
396.715779872694
514.39429429184
404.442344469518
476.846474245118
599.020867750031
429.163139144079
514.941744277933
445.426761656729
531.013596812737
374.977332648255
364.660115724218
538.306752697753
519.042387479096
1412.54699036882
405.571202133485
516.606049132218
2289.49623498271
378.228766753667
504.730621222846
358.715764917016
462.339366699398
512.429858614816
394.778786157514
366
498.760463549388
366.552861126468
355.37022947906
358.308526273099
376.745272034036
366.934599077274
536.0901883079
483.01740134285
508.975480745389
365.629593988233
536.368800360349
557.024236456548
366.776498701866
501.007025898839
330.686029339009
508.395475983019
429.563732174866
2224.68806802212
534.655786464525
518.711297351426
534.304229816684
514.941744277933
420.32368479542
367.129404978681
525.626188464768
388.329756778952
1251.30895065927
525.626188464768
412.313764019587
513.697381733643
506.675438520558
1517.71183364959
550.276294237722
543.359917550053
500.639590923451
395.129864728041];
Histogram computation:
[nelements,centers] = hist(d1);
nelements=55 13 0 0 1 1 1 0 0 2
I want to remove all points apearing less than 5 (in nelements). It means only first 2 elements in nelements( 55, 13 ) remains.
Is there any function in matlab.
You can do it along these lines:
threshold = 5;
bin_halfwidth = (centers(2)-centers(1))/2;
keep = ~any(abs(bsxfun(#minus, d1, centers(nelements<threshold))) < bin_halfwidth , 2);
d1_keep = d1(keep);
Does this do what you want?
binwidth = centers(2)-centers(1);
centersOfRemainingBins = centers(nelements>5);
remainingvals = false(length(d1),1);
for ii = 1:length(centersOfRemainingBins )
remainingvals = remainingvals | (d1>centersOfRemainingBins (ii)-binwidth/2 & d1<centersOfRemainingBins (ii)+binwidth/2);
end
d_out = d1(remainingvals);
I don't know Matlab function for this problem, but I think, that function with follow code is what are you looking for:
sizeData = size(data);
function filter_hist = filter_hist(data, binCountRemove)
if or(max(sizeData) == 0, binCountRemove < 1)
disp('Error input!');
filter_hist = [];
return;
end
[n, c] = hist(data);
sizeN = size(n);
intervalSize = c(2) - c(1);
if sizeData(1) > sizeData(2)
temp = transpose(data);
else
temp = data;
end
for i = 1:1:max(sizeN)
if n(i) < binCountRemove
a = c(i) - intervalSize / 2;
b = c(i) + intervalSize / 2;
sizeTemp = size(temp);
removeInds = [];
k = 0;
for j = 1:1:max(sizeTemp)
if and(temp(j) > a, less_equal(temp(j), b) == 1)
k = k + 1;
removeInds(k) = j;
end
end
temp(removeInds) = [];
end
end
filter_hist = transpose(temp);
%Determines when 'a' less or equal to 'b' by accuracy
function less_equal = less_equal(a, b)
delta = 10^-6; %Accuracy
if a < b
less_equal = 1;
return;
end
if abs(b - a) < delta
less_equal = 1;
return;
end
less_equal = 0;
You can do something like this
nelements=nelements((nelements >5))

incapsulation of a code inmatlab

my code is
pathname=uigetdir;
filename=uigetfile('*.txt','choose a file name.');
data=importdata(filename);
element= (data.data(:,10));
in_array=element; pattern= [1 3];
locations = cell(1, numel(pattern));
for p = 1:(numel(pattern))
locations{p} = find(in_array == pattern(p));
end
idx2 = [];
for p = 1:numel(locations{1})
start_value = locations{1}(p);
for q = 2:numel(locations)
found = true;
if (~any((start_value + q - 1) == locations{q}))
found = false;
break;
end
end
if (found)
idx2(end + 1) = locations{1}(p);
end
end
[m2,n2]=size(idx2)
res_name= {'one' 'two'};
res=[n n2];
In this code I finding a pattern in one of the column of my data file and counting how many times it's repeated.
I have like 200 files that I want to do the same with them but unfotunatlly I'm stuck.
this is what I have added so far
pathname=uigetdir;
files=dir('*.txt');
for k=1:length(files)
filename=files(k).name;
data(k)=importdata(files(k).name);
element{k}=data(1,k).data(:,20);
in_array=element;pattern= [1 3];
locations = cell(1, numel(pattern));
for p = 1:(numel(pattern))
locations{p} = find(in_array{k}== pattern(p));
end
idx2{k} = [];
how can I continue this code..??
OK, first define this function:
function [inds, indsy] = findPattern(M, pat, dim)
indices = [];
if nargin == 2
dim = 1;
if size(M,1) == 1
dim = 2; end
end
if dim == 1
if numel(pat) > size(M,1)
return; end
for ii = 1:size(M,2)
inds = findPatternCol(M(:,ii), pat);
indices = [indices; repmat(ii,numel(inds),1) inds]%#ok
end
elseif dim == 2
if numel(pat) > size(M,2)
return; end
for ii = 1:size(M,1)
inds = findPatternCol(M(ii,:).', pat);
indices = [indices; inds repmat(ii,numel(inds),1)]%#ok
end
else
end
inds = indices;
if nargout > 1
inds = indices(:,1);
indsy = indices(:,2);
end
end
function indices = findPatternCol(col, pat)
inds = find(col == pat(1));
ii = 1;
prevInds = [];
while ~isempty(inds) && ii<numel(pat) && numel(prevInds)~=numel(inds)
prevInds = inds;
inds = inds(inds+ii<=numel(col) & col(inds+ii)==pat(ii+1));
ii = ii + 1;
end
indices = inds(:);
end
which is decent but probably not the most efficient. If performance becomes a problem, start here with optimizations.
Now loop through each file like so:
pathname = uigetdir;
files = dir('*.txt');
indices = cell(length(files), 1);
for k = 1:length(files)
filename = files(k).name;
data(k) = importdata(files(k).name);
array = data(1,k).data(:,20);
pattern = [1 3];
indices{k} = findPattern(array, pattern);
end
The number of occurrences of the pattern can be found like so:
counts = cellfun(#(x)size(x,1), indices);