write a function to return next value each time only nonzeros

2 visualizzazioni (ultimi 30 giorni)
Hi
I want to write a function to return the value of gmax_gholhak each time there are some numbers i.e 0 45 0 0 0 75 and I want to return only nonzeros value in each time i call the function first time 45 second 75 and ....... .but it return all data in the array regardless the condition in if and also zeros in it . and also when i write my code like this in if statement " gmax_gholhak" (without i ) it only returns the last value.
I also use nonzeros but it didn't help neither
can you help me , Thank you very much
function [gmax_gholhak] = Gmax_gh(k)
gholhak_gmin = readtable('gholhak_gmin.xlsx');
gholhak_queue = readtable('gholhak_queue.xlsx');
mir_gmin = readtable('mir_gmin.xlsx');
mir_queue = readtable('mir_queue.xlsx');
gholhak_period_down =gholhak_gmin.begin(17:end,1);
gholhak_car_number_min = gholhak_gmin.nVehContrib(17:end,:);
gholhak_period_up =gholhak_queue.begin(17:end,1);
gholhak_car_number_queue = gholhak_queue.nVehContrib(17:end,:);
mirdamad_period_up =mir_queue.begin(17:end,1);
mir_car_number_queue = mir_queue.nVehContrib(17:end,:);
mir_period_down =mir_gmin.begin(17:end,1);
mir_car_number_min = mir_gmin.nVehContrib(17:end,:);
%% Calculate Green time min-max
N = length(gholhak_car_number_queue)/2;
for i = 1:1:N
gmin_gholhak = 0;
if gholhak_car_number_queue(2*i-1) + gholhak_car_number_queue(2*i) ==0
gmax_gholhak(i) =(gholhak_period_up(2*i-1) + gholhak_period_up(2*i))/2;
end
end
end

Risposta accettata

Jonas
Jonas il 6 Ott 2022
if I understand correctly you want the function the be able to remember how often the function was called. each time the next non-zero element is the output
a brief implementation could look like this:
array=[1 0 0 2 0 0 3 0 0 0 4 5 0 0];
getNextNonzero(array)
ans = 1
getNextNonzero(array)
ans = 2
getNextNonzero(array)
ans = 3
getNextNonzero(array)
ans = 4
getNextNonzero(array)
ans = 5
getNextNonzero(array)
no element left
ans = NaN
function out=getNextNonzero(array)
array=array(array~=0);
persistent idx;
if isempty(idx);
idx=1;
elseif idx<numel(array)
idx=idx+1;
else
disp('no element left');
out=NaN;
return;
end
out=array(idx);
end

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by