0
votes

I am trying to create a column vector in matlab based on two 64x64 double vectors, and iterate through each element in the vector and apply an equation to create a new vector, which will then be applied. Here is my code

for i=1:4096,

vector1 = v1(:); %instead of copying the vector this created a 4096X1 double rather than 64X64 for some reason, same with vector2
vector2 = v1(:);
vector1(i) = vector1(i) + 0.05*vector2(i); %for each element in vector1 apply equation to update values.
end
v1(:) = vector1(:); % replace v1 with the new vector1 created on the equation applied 

As far as I see this should work, however instead of creating a 64*64 vector a 1*4096 vector is created and I am getting a mismatch error because the vectors are not the same.

2

2 Answers

0
votes

The resulting vector is a column vector because that's the output of linear indexing (indexing with a only a single subscript). It's also worth noting that the conversion to a column vector is redundant, linear indexing does that implicitly.

If you want the final result to be a 64x64 matrix, initialize the result array with the appropriate size to begin with:

result = zeros(size(v1)); %// Same dimensions as v1, i.e 64-by-64

and let MATLAB automatically convert linear indices into the corresponding position in the result matrix. Alternatively, you can use reshape, for example:

result = reshape(v1, 64, 64);

In addition, I believe that your loop's logic is indeed broken in more than one place:

  1. You're overwriting the values of vector1 and vector2 in each iteration. Put the their initialization lines before the loop.
  2. You're assigning the wrong values into vector2... shouldn't it be vector = v2(:) or something?

The final loop should look like this:

result = zeros(size(v1));
for k = 1:numel(v1),
    result(k) = v1(k) + 0.05 * v2(k);
end
0
votes
vector1 = v1;
for i=1:64
    for j = 1:64
        vector1(i, j) = vector1(i, j) + 0.05*v1(i, j);
    end
end
v1 = vector1;     % or v1 = vector1(:, :); if you prefer

No vector2 matrix is needed for this process.