MATLAB Answers

How do I prevent overwriting of matrix elements?

55 views (last 30 days)
The matrix elements start writing correctly, but as soon as the next one gets written, all preceeding elements also get the next value applied to them for some reason. This just leaves me with the last value of the V vector as all first column and row elements
n = 5; % Matrix will be (n+1)x(n+1)
V = ZeroBased(zeros(1,n));
for i = 1:n
V(i) = i/3;
end
H = ZeroBased(zeros(n));
for cols = 0:n
for rows = 0:n
if cols == 0 % Only column 1
H(1:rows,cols) = V(rows);
elseif rows == 0 % Only row 1
H(rows,1:cols) = V(cols);
elseif rows == cols % Only diagonal (excluding 1,1 for some reason)
H(rows,cols) = rows^2 + sum(V);
else
H(rows,cols) = V(rows); % Remainder of cells
end
H(0,0) = sum(V_vals) % Necessary to have an exception statement for 1,1
end
end
I've included comments so you can see my train of thought to some degree.
  3 Comments

Sign in to comment.

Accepted Answer

David Goodmanson
David Goodmanson on 4 Feb 2021
Hi Domantas
This is just a provisional answer since I am not sure exactly what you are trying to do, but statements like
H(1:rows,cols) = V(rows); and H(rows,1:cols) = V(cols);
ensure that previous rows and columns of H are going to be overwritten, as opposed to
H(rows,cols) = whatever
  5 Comments
Domantas Laurinavicius
Domantas Laurinavicius on 5 Feb 2021
Oh, huh, it was that simple. Thanks very much!
Edit, this is the equation I'm trying to fit to the matrix:

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 5 Feb 2021
To prevent overwriting of matrix elements, you could define a new class that stored an array, and also stored a map of which elements had been written to so far. Define a subsasgn method for it that checked the subscripts to be assigned to against the list of locations already written to, and then do one of:
  • issue an error
  • issue a warning and skip re-assigning to those particular locations and continue
  • skip re-assigning to those locations and silently continue
You would also want to define all the usual mathematical operations on the array.
When you do define the usual mathematical operations, one question would be what you want to do if the operation requests read access to locations that the user had not requested to write to yet.

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!