Reputation: 111
So i have a 1xn matrix x and the for loop calculates the absolute value of differences in consecutive entries of x starting with entry 3.
n=length(x);
for i=3:n
y=abs(x(i)-x(i-1));
what i need my output to be is a 2 column vector. First column displays x and second column displays zeros for the first two rows followed by the results of the for loop.
x is a loaded vector
this is my function function [ z ] = dome(x)
n=length(x);
z = zeros(n, 2);
for i=3:n;
z(3:n,2)=abs(x(i)-x(i-1));
z(:,1) = x;
end
I'm getting this as output
ans =
1.000000000000000 0 1.500000000000000 0 1.286953767623375 0.000009575517218 1.402540803539578 0.000009575517218 1.345458374023294 0.000009575517218 1.375170252816038 0.000009575517218 1.360094192761733 0.000009575517218 1.367846967592133 0.000009575517218 1.363887003884021 0.000009575517218 1.365916733390040 0.000009575517218 1.364878217193677 0.000009575517218 1.365410061169957 0.000009575517218 1.365137820669213 0.000009575517218 1.365277208524479 0.000009575517218 1.365205850297047 0.000009575517218 1.365242383718839 0.000009575517218 1.365223680225282 0.000009575517218 1.365233255742500 0.000009575517218
Upvotes: 1
Views: 174
Reputation: 879
In MATLAB there is a "big" difference between 0
and 0.0000
. The former is really zero while the latter can be almost as big as 0.00005
. You can "fix" it by changing the output format with format long
. You also need to use i
in the assignment ...
format long;
n=length(x);
z = zeros(n, 2);
z(:,1) = x;
for i=3:n;
z(i,2)=abs(x(i)-x(i-1));
end
Upvotes: 1
Reputation: 7751
You can do it this way. The code uses the matlab's diff
function.
x = rand(1,10) % vector of 1x10
y = [x' [0 ; abs(diff(x))']];
y(1:3,:) = [];
This gives
y =
0.0462 0.2308 0.0971 0.0510 0.8235 0.7263 0.6948 0.1286 0.3171 0.3777 0.9502 0.6331 0.0344 0.9158
If you want to keep the for loop, this code
Y = zeros(length(x), 2); %create the output matrix Y
Y(1:2, 1) = x(1:2); %popualte the first 2 row of column 1 with x(1:2) // thanks to @Dan
for i=3:length(x);
Y(i, 1) = x(i); %populate the first column
Y(i, 2) = abs(x(i)-x(i-1)); %populate the second column
end
gives
Y =
0.7513 0 0.2551 0 0.5060 0.2509 0.6991 0.1931 0.8909 0.1918 0.9593 0.0684 0.5472 0.4121 0.1386 0.4086 0.1493 0.0107 0.2575 0.1082
Upvotes: 1