Member • Nov 18, 2009
Subscripted assignment dimension mismatch: Matlab Error
Hi Everyone,
I have stored a few values in a structure. I am using the getfield()
function and after getting the value of a single element that satisfies a condition, I'm storing it in a variable varx
.
The situation is like this:
for i = 1:4
for n = 1:4
varx(i, n) = getfield(J, {n, 1}, 'val');
end
end
The 'val' field of the structure has values in the form j1, j2, ..., j15. J
is the name of the structure.
I have no problem if the 'val' field has values up to 'j9'. But when the selected value is in the range j10,...,j15, I get the following error:
??? Subscripted assignment dimension mismatch
.
Any help in this regard is highly appreciated.
Regards
Update: Answer
The issue you're facing seems to be related to the dimensions of the varx
variable, and the code snippet you've posted has an emoji in it, so it might not represent the exact problem. But I'll do my best to explain what could be going wrong.
1. **Dimensions of varx
**: Before the loop, you should pre-allocate varx
with the proper size, so that the assignment inside the loop matches the expected dimensions. In the loop, you are iterating over both i
and n
from 1 to 4, but the assignment isn't clear due to the emoji.
2. **Value of 'val' field**: You mentioned that the 'val' field has values up to 'j15'. It's unclear if this means the 'val' field is a numeric array, character array, or cell array. The structure of the 'val' field might lead to a mismatch with the varx
dimensions when you try to assign the value.
3. **Using getfield
**: In modern versions of MATLAB, it's more common to access fields of a structure using dot notation rather than the getfield
function. For example, you could use J(n,1).val
instead of getfield(J,{n,1}, 'val')
. This might simplify your code and help identify the problem.
Here's a revised version of your code snippet, assuming J
is a 4x1 structure array, and the 'val' field is a vector of numbers:
varx = zeros(4, 4); % Pre-allocate varx
for i = 1:4
for n = 1:4
varx(i, n) = J(n,1).val(i); % Access the 'val' field using dot notation
end
end
This code assumes that each 'val' field is a vector containing at least 4 elements. If the 'val' field has a different structure, please clarify, and I can provide more specific assistance.