mapping of matrices with different size
Afficher commentaires plus anciens
i have to map the values from a matrix to another one based on the value in the first column: i used the following code
data = [0 1;0.1 2;0.2 3;0.3 4; 0.6 5 ;0.7 6;0.8 7;1 8]
[m,n]=size(data);
StopTime=1;
SampleTime=0.1;
TimeStep=(StopTime/SampleTime)+1;
initial=0
time=zeros(TimeStep,n)
for i=1:TimeStep
time(i,1)=initial;
initial=initial+SampleTime;
end
c=0;
for j=1:TimeStep
for i=1:m
if (data(i,1)==time(j,1))
time(j,2)=data(i,2);
end
end
end
the expected result is
[0 1;
0.1 2;
0.2 3;
0.3 4;
0.4 0;
0.5 0;
0.6 5;
0.7 6;
0.8 7;
0.9 0;
1 8]
but the obtained result is:
[0 1;
0.1 2;
0.2 3;
0.3 0;
0.4 0;
0.5 0;
0.6 5;
0.7 6;
0.8 0;
0.9 0;
1 0]
please hel p me to fix this issue
1 commentaire
Stephen23
le 21 Jan 2015
Note that you should not use i or j for the names of your loop variables, as these are the names of the inbuilt imaginary unit .
Réponse acceptée
Plus de réponses (1)
Thorsten
le 21 Jan 2015
Stephen made some remarks that are useful in general, but in your case you can get along with
newdata(:,1) = 0:0.1:1; % first column
newdata(10*data(:,1)+1, 2) = data(:,2); % second column
The idea is to use the first column of data as an index. Because the values run from 0 to 1 in steps of 0.1, you can convert it to a valid Matlab index by multiplication with 10 and adding 1 (Matlab's indices always start with 1). Missing values in the index (such as 4, 5 and 9) are automatically set to zero by Matlab.
2 commentaires
Although this then mixes the data and indexing, by making the indexing a by-product of the data itself. It will fail, for example, with negative data values. Keeping the indexing independent from the data results in more robust and versatile code.
Rani V.S
le 22 Jan 2015
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!