generate average numbers between two numbers inside a vector
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi! It is easier with the figure than with words. I want to create average numbers between two numbers and insert them instead of '0's.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1626278/image.png)
V = [3.4789; 0; 0; 3.3535; 0; 0; 3.2398; 3.2263; 0; 0; 0; 3.0846; 0; 0; 2.9815; 0; 2.9430; 0; 2.9055];
r0 = [2;3;5;6;9;10;11;13;14;16;18]; %rows with 0
r1 = [1;4;7;8;12;15;17;19];
% at the moment: mean
vect_mean = {};
for b = 1:height(r1)
v1 = V(r1(b),4);
v2 = V(r1(b+1),4);
vv = [v1; v2];
vv_mean = mean(vv);
vect_mean = [vect_mean;{vv_mean}];
end
댓글 수: 0
채택된 답변
Star Strider
2024년 2월 24일
편집: Star Strider
2024년 2월 24일
One approach —
V = [3.4789; 0; 0; 3.3535; 0; 0; 3.2398; 3.2263; 0; 0; 0; 3.0846; 0; 0; 2.9815; 0; 2.9430; 0; 2.9055];
r0 = [2;3;5;6;9;10;11;13;14;16;18]; %rows with 0
r1 = [1;4;7;8;12;15;17;19];
L = numel(r1);
mvc = accumarray(r1, (1:numel(r1)).', [], @(x){mean(V([r1(x) r1(min([x+1,L]))]))});
Lv = cellfun(@(x)isempty(x), mvc, 'Unif',0);
mvc([Lv{:}]) = {NaN};
mv = cell2mat(mvc);
mv = fillmissing(mv,'previous');
V([Lv{:}]) = mv([Lv{:}])
Vbfr = buffer(V,10) % Display Entire Vector In Columns
Vm = V;
V = [3.4789; 0; 0; 3.3535; 0; 0; 3.2398; 3.2263; 0; 0; 0; 3.0846; 0; 0; 2.9815; 0; 2.9430; 0; 2.9055];
Comparison = table(V, Vm, 'VariableNames',{'Original','Filled'})
First_10_Rows = Comparison(1:10,:)
Last_9_Rows = Comparison(11:end,:)
The accumarray call calculates the mean values, then computes logical vector ‘Lv’ to detect the empty cells that are then filled with NaN values. The ‘mvc’ cell array is then converted to a numerical array, and the NaN values are filled with the previous result using the fillmissing funciton. The ‘Lv’ vector us used again to fill the zeros in the original ‘V’ vector with the corresponding elements from ‘mv. to provide the result.
EDIT — (24 Feb 2024 at 15:46)
Added ‘Comparison’ table and sub-tables from it, extended the discussion of how the code works.
.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Preprocessing Data에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!