Zeroing matrix elements outside of a certain range.
Ältere Kommentare anzeigen
edit: I changed my data example input because it was a bad example that accepted some solution that are not going to work in general
Hi guys, I would like to zero the outer elements of a matrix so that they are not counted in a sum / average.
Basically the matrix is experimental data and each column comes from a different experiment and the first and last datapoints in each experiment are likely to be artefact.
for example:
data = rand(5,2)
and I would like to keep the points 1:4 in the first column (experiment 1) and 2:5 in the second column (experiment 2).
Ideally, I would like to input a matrix of bounds of valid range:
range = [1,4;2,5]
and I would like the data for the index not in that range to be zeroed and ideally without a loop
like
data(index<range(1,:) or index>range(2,:)) = 0
but of course this is not the right line...
A long way would be:
remove = ones(5,2)
remove(range(1,1):range(1,2),1) = 0
remove(range(2,1):range(2,2),2) = 0
data(remove)=0
ah no, even that doesn't work. But even if it would, that's way too inefficient. Sorry, really struggling...
Antworten (2)
A simple approach via indexing -
data = [1;2;3;4;5].*ones(5,2).*[0.5,0.4]
out = [data(1:4,1) data(2:5,2)]
4 Kommentare
Dyuman Joshi
am 29 Feb. 2024
Bearbeitet: Dyuman Joshi
am 5 Mär. 2024
The Gogo
am 5 Mär. 2024
Zeroing the data will not exclude it from the average. You should use NaNs,
data = [1;2;3;4;5].*ones(5,2).*[0.5,0.4]
range = [1,0;
inf,1.7]
data(range(1,:)>data | data>range(2,:))=nan
Average=mean(data,1,'omitnan')
4 Kommentare
Dyuman Joshi
am 29 Feb. 2024
You are assuming that the comparison is made w.r.t some values.
However, the selection of data here is to be done w.r.t values being treated as indices.
The Gogo
am 15 Apr. 2024
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!