1

I'm trying to apply a function to a vector where for each new row the same function applies but a variable changes. So for example if I have a vector with N rows:

A = [1.2; 1.5; 1.8; 2.3; 2.7; 2.8; 2.9];

I want to subtract n*0.1 away from each row where n = row number. So 1.5 in row 2 would be subtracted by 0.2 (2*0.1), 2.8 in row 6 would be subtracted by 0.6 (0.1*6), and so on.

To clarify I would like a function that says to my file, OK this is row n and I want to subtract the number in row n by n multiplied by 0.1. I would like the code to be able to read the file row by row so the end result is a vector that has done the above to each row. I think a loop would be needed?

I'm sure the solution is simple but I don't know how to do it.

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
user3536870
  • 249
  • 1
  • 2
  • 13

1 Answers1

5

I believe this should do the trick:

A
    1.2000
    1.5000
    1.8000
    2.3000
    2.7000
    2.8000
    2.9000

b = A-(1:numel(A)).'*0.1
b =
    1.1000
    1.3000
    1.5000
    1.9000
    2.2000
    2.2000
    2.2000

What it does is it creates a column vector with values 1:numel(A), so [1; 2; 3 ...], then multiplies each of these values by 0.1. This vector is then subtracted from the original vector.

As you see, there is a dot, .', in there. It is not really necessary here, but it's good practice to include it. Without the dot, ' would make a conjugate transpose, in stead of a regular one. The transpose of course, converts the horizontal vector to a vertical one.

To satisfy Divakar, who can make dinner and build a house at the same time using only bsxfun, permute and reshape:

If you wanted to do this with a matrix instead, you could use repmat, or meshgrid, or the much more awesome bsxfun, like this:

A = magic(5);

b = bsxfun(@minus, A, [1:size(A,1)].'*0.1)
b =
   16.9000   23.9000    0.9000    7.9000   14.9000
   22.8000    4.8000    6.8000   13.8000   15.8000
    3.7000    5.7000   12.7000   19.7000   21.7000
    9.6000   11.6000   18.6000   20.6000    2.6000
   10.5000   17.5000   24.5000    1.5000    8.5000

More dimensions? Combine bsxfun and permute.

Community
  • 1
  • 1
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70