How to subtract the elements in one matrix with the corresponding elements in another matrix?

10 visualizaciones (últimos 30 días)
I'm doing a project work at the university in a course about Statistic methods of Earth Science. In this project we shall analyze a datafile with gravity measurements from the northern part of Sweden. The data file contains totally 3882 measure points. A part of the project work is to randomly exclude 300 measurements points from the original data file. A new matrix shall then be created where the 300 randomly selected measurement points have been deleted from the original data matrix. How to implement this in matlab? I tried this code:
clear
data = load('Mala_grav.txt');
Gravity = data(:,3); % data file with gravity measurements
[y,idx] = datasample(Gravity,300); % randomly pick out 300 measurement points
idx2 = sort(idx); % sort the index in increasing order
for i=1:length(Gravity)
for j=1:1:length(idx2)
if i==idx2(j) % compare index in the original data with the index in the vector with the 300 randomly chosen measurements points
G2(i)=0; % set value to zero if i = j
else
G2(i)=Gravity(i);
end
end
end
--------------
Problem: The 300 randomly chosen data points are not excluded in the new data matrix G2. How to subtract these values from the elements of the original data matrix?
Hope someone can give me a clue to solve this problem?!
Thanks in advance!
/Mattias

Respuestas (1)

Bjorn Gustavsson
Bjorn Gustavsson el 23 de Mayo de 2020
You're not asking for values to subtract, but indices to not include. My simple suggestion is that you take a look at the randperm function. You should be able to use that function to generate an array of indices to not include. You should be able to adapt this snippet:
data = randn(17,3);
idx2all = randperm(size(data,1));
idx2skip = idx2all(1:5);
data5shorter = data;
data5shorter(idx2skip,:) = [];
HTH
  9 comentarios
Bjorn Gustavsson
Bjorn Gustavsson el 11 de Jun. de 2020
Good.
(Sound programming advice: Try to make small test-cases that you can run and look at the results element-by-element and simple cases that you can figure out manually. That way you have an easy way to check that your functions have the correct behaviour. Then you can scale up in size and whatnots. Apply as appropriate.)
Mattias Larsson
Mattias Larsson el 11 de Jun. de 2020
Ok. I will try to follow this strategy next I get trouble with my matlab programming. :-)

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by