简体   繁体   中英

Subscripted assignment dimension mismatch when combining corresponding array and cell array values in matlab

I have an array and a cell array with the same dimensions: A is a 1x2492 double array, and B is an 1x2492 cell cell array. I want to make a new cell array that assigns the values in A to the corresponding column values of B. Here was my code:

for n = 1:numel(B)
    newArray(n) = [A(n),B{n}(2)];
    newCellArray{n} = newArray;
end

When I ran the code, I got the error 'Subscripted assignment dimension mismatch.'

I think it's because some cells in B have multiple columns, and the code loop doesn't recognize that I want to assign the same value of A to all values in the cell.

For example, if cell 1 of B contains:

2      2355
23     1293
37     1222

I would like my code loop to assign the corresponding first value of A to 2355, 1293, and 1222. So basically, I'd like to have a new cell like this:

1      2355
1      1293
1      1222

I realize that this is a very confusing explanation, but I hope that it makes sense. Any and all help would be greatly appreciated - thank you very much!

Try:

newCellArray = cell(numel(B),2);
for n = 1:numel(B)
    lenB = length(B{n}(2));
    newA = repmat(A(n),lenB);
    newArray = [newA,B{n}(2)];
    newCellArray = [newCellArray; newArray];

end

I am not really sure what you are trying to do, but the code below will assign the value of A(ii) to every element in the first column of B{ii} . I am just saying this based on your example, but your explanation is really unclear..

C = B;
for ii=1:numel(C)
    C{ii}(:,1)=A(ii);
end

And you are getting an error on newArray(n) = [A(n),B{n}(2)]; because you are trying to assign a vector to a singleton dimension. Try a(1) = [1 2] and you will still get an error, and this is independent on what your cell dimensions are, etc.. a(1,:)=[1 2] , however, might work if the 2nd dimension of a is 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM