Subscripted assignment dimension mismatch матлаб ошибка

The line:

new_img(rows,cols,:) = curMean;

will only work if rows and cols are scalar values. If they are vectors, there are a few options you have to perform the assignment correctly depending on exactly what sort of assignment you are doing. As Jonas mentions in his answer, you can either assign values for every pairwise combination of indices in rows and cols, or you can assign values for each pair [rows(i),cols(i)]. For the case where you are assigning values for every pairwise combination, here are a couple of the ways you can do it:

  • Break up the assignment into 3 steps, one for each plane in the third dimension:

    new_img(rows,cols,1) = curMean(1);  %# Assignment for the first plane
    new_img(rows,cols,2) = curMean(2);  %# Assignment for the second plane
    new_img(rows,cols,3) = curMean(3);  %# Assignment for the third plane
    

    You could also do this in a for loop as Jonas suggested, but for such a small number of iterations I kinda like to use an «unrolled» version like above.

  • Use the functions RESHAPE and REPMAT on curMean to reshape and replicate the vector so that it matches the dimensions of the sub-indexed section of new_img:

    nRows = numel(rows);  %# The number of indices in rows
    nCols = numel(cols);  %# The number of indices in cols
    new_img(rows,cols,:) = repmat(reshape(curMean,[1 1 3]),[nRows nCols]);
    

For an example of how the above works, let’s say I have the following:

new_img = zeros(3,3,3);
rows = [1 2];
cols = [1 2];
curMean = [1 2 3];

Either of the above solutions will give you this result:

>> new_img

new_img(:,:,1) =

     1     1     0
     1     1     0
     0     0     0

new_img(:,:,2) =

     2     2     0
     2     2     0
     0     0     0

new_img(:,:,3) =

     3     3     0
     3     3     0
     0     0     0

This error occurs when you attempt to assign elements to an existing array, but the size of the variable you are trying to assign is not compatible with the existing array. For example, the following code snippet produces this error:

A = [1 2 3; 4 5 6];

B = [7 8 9 10];

A(2,:) = B

In this case, ‘A’ has size 2×3, that is, 2 rows and 3 columns. The vector ‘B’ has size 1×4, 1 row and 4 columns. The assignment statement attempts to replace the second row of ‘A’ with the row vector ‘B’, but this is not possible because ‘B’ has 4 columns, and ‘A’ only has 3 columns. In order to assign to the second row of ‘A’, you must use a vector with 3 columns. For example,

B = [11 12 13];

A(2,:) = B

For more information on indexing in MATLAB, see the following documentation page:

khiggs2013

0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

1

Matlab 2014

20.06.2018, 10:55. Показов 8368. Ответов 12

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

m-file1

Matlab M
1
2
3
4
function z=Bz(x0,y0,a,h,N)
psi=0:pi/50:2*pi*N;
F=f(psi,x0,y0,a,h);
z=trapz(psi,F);

m-file2

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
function F=f(psi,x0,y0,a,h)
Nx=length(x0);
Ny=length(y0);
for i=1:Nx
    s=0;
    for j=1:Ny      
        s=s+((y0(j)-a*sin(psi))*a.*sin(psi)+a*cos(psi).*(x0(i)-a*cos(psi)))./...
(x0(i)^2+y0(j)^2+a^2+(h/(2*pi)*psi).^2-...
2*(x0(i)*a*cos(psi)+a*y0(j)*sin(psi))).^(3/2);
     end;
       M(i,j)=s;
end;
F=M;

код программы:

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
N1=21;
i=1:N1+1;
j=1:N1;
x0min=0; y0min=0;
x0max=5; y0max=5;
x0(i)=x0min+(x0max-x0min)/N1*(i+1);
y0(j)=y0min+(y0max-y0min)/N1*(j+1);
a=1;
h=0.1;
N=1;
[x01,y01]=meshgrid(x0,y0);
mp=Bz(x0,y0,a,h,N);
contourf(x0,y0,mp,50);

Ошибки:
>> Test2
Subscripted assignment dimension mismatch.

Error in f (line 11)
M(i,j)=s;

Error in Bz (line 4)
F=f(psi,x0,y0,a,h);

Error in Test2 (line 13)
mp=Bz(x0,y0,a,h,N);



0



6687 / 4779 / 1998

Регистрация: 02.02.2014

Сообщений: 12,798

20.06.2018, 11:01

2

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

M(i,j)=s;

это должно быть внутри цикла

Добавлено через 49 секунд
на форуме есть теги matlab [MATLAB ] [ /MATLAB] — четвертый справа в первом ряду



0



0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

21.06.2018, 12:35

 [ТС]

3

Ребята, кто может подсказать что сделать с этим?



0



Модератор

Эксперт по математике/физике

5146 / 3947 / 1364

Регистрация: 30.07.2012

Сообщений: 11,831

21.06.2018, 13:26

4

khiggs2013, а вот что…

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

M(i,j)=s;

это должно быть внутри цикла



0



0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

21.06.2018, 13:46

 [ТС]

5

Дык я её внутрь цикла и помещал, то есть выше end , но результата то нет



0



Модератор

Эксперт по математике/физике

5146 / 3947 / 1364

Регистрация: 30.07.2012

Сообщений: 11,831

21.06.2018, 13:52

6

khiggs2013, а ничего, что там есть еще один, вложенный цикл?



0



0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

21.06.2018, 13:55

 [ТС]

7

Дак что сделать то технически надо?



0



SSC

Эксперт по математике/физике

3385 / 1908 / 571

Регистрация: 09.04.2015

Сообщений: 5,350

21.06.2018, 15:22

8

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

Дык я её внутрь цикла и помещал, то есть выше end , но результата то нет

Конечно присвоение
M(i,j)=s;
должно быть выше еще одного end судя по индексу j, однако проблема в другом.
У Вас s получается массивом 1х101, из-за того что psi массив. И тут надо разбираться что Вы там и как интегрируете. Мне физика Вашей задачи неизвестна.
Из синтаксиса MATLABa возможно поставить присвоение

Matlab M
1
M{i,j}=s;

Однако перед интегрированием надо разбираться что с полученными данными делать.



0



0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

22.06.2018, 00:19

 [ТС]

9

Цитата
Сообщение от SSC
Посмотреть сообщение

У Вас s получается массивом 1х101,

А не могли бы вы пояснить как вы подсчитали массив что размерность его 1 на 101?



0



SSC

Эксперт по математике/физике

3385 / 1908 / 571

Регистрация: 09.04.2015

Сообщений: 5,350

22.06.2018, 08:18

10

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

как вы подсчитали массив что размерность его 1 на 101?

Вот эта строка

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

Matlab M
1
psi=0:pi/50:2*pi*N;

дает 101 элемент.
Но можно и не считать, а просто в отладчике поставить точку останова, и посмотреть размер массива



0



0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

22.06.2018, 19:20

 [ТС]

11

Цитата
Сообщение от SSC
Посмотреть сообщение

дает 101 элемент

Ага. понял. Ну скорее наверное 101*N так как N в моей задаче это число витков соленоида.
Дело в том, что все должно там вроде бы работать(где происходит интегрирование). Выражение

Цитата
Сообщение от SSC
Посмотреть сообщение

1
psi=0i/50:2*pi*N;

определяет в функции

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

z=trapz(psi,F)

пределы интегрирования, как я понял из: http://old.exponenta.ru/soft/m… /trapz.asp

Вообщем в моей задаче нужно взять например M(5, 6) (ну вот это:

Цитата
Сообщение от khiggs2013
Посмотреть сообщение

M(i,j)=s;

) и проинтегрировать его от 0 до 2*pi*N. Далее вынести на сетку по X=5, а по Y=6. И так перебрать каждый i и j.



0



Эксперт по математике/физике

3385 / 1908 / 571

Регистрация: 09.04.2015

Сообщений: 5,350

22.06.2018, 21:38

12

Лучший ответ Сообщение было отмечено khiggs2013 как решение

Решение

Сущность проблемы мне не понятна, но возможно надо проводить интегрирование сразу перед присвоением
M(i,j)=s;
и в массиве хранить уже результаты интегрирования



1



0 / 0 / 0

Регистрация: 28.09.2016

Сообщений: 10

23.06.2018, 17:02

 [ТС]

13

Спасибо за помощь SSC!
Все таки надо было сначала интегрировать а потом уж перебирать по i , j.
Ответ получил в виде вот такого распределения. Это компонента по z магнитного поля однослойного соленоида рассчитанная по закону Био Савара в плоскости z-y.

Миниатюры

Ошибка: Subscripted assignment dimension mismatch. Почему ?
 



0



In this Insight, I’ll go over 5 common MATLAB error messages, what they mean, and how to fix them. Hopefully, after reading this post you’ll find yourself being more productive, and maybe even help your friends with their code.

Most forums online where people post MATLAB questions generate quite a bit of duplicates, and PhysicsForums is no exception. The fact is, there are just certain situations that come up constantly in MATLAB, and if you’re a newer user, don’t consider yourself a programmer, or haven’t used the software in a while, then you’re likely to get tripped up and receive one of those red error messages. It can be especially frustrating when the message doesn’t make sense to you, or your best efforts to fix it come up dry.

Table of Contents

1. Error using * Inner matrix dimensions must agree.

By far the most common error message I see posted about by new users is this one. They create a few matrices or vectors and just go to multiply them with A*B, and this message is returned. Some example code that produces this message is:

A = [1 2 3];
B = [4 5 6];
A*B
Error using * 
Inner matrix dimensions must agree.

The key to this error message is usually that people are not aware of the elementwise operators in MATLAB. The * operator performs matrix multiplication, where an NxM matrix is multiplied by an MxP matrix, resulting in an NxP matrix. Notice how those matrices have the common dimension “M”? That’s where this message comes from; it’s a common inner dimension.

Most often, you simply need to use .* instead of * to perform the elementwise multiplication, where corresponding elements are multiplied and the result is the same size as the inputs.

A.*B

ans =

     4    10    18

For more information about the different MATLAB operators, see Array vs. Matrix Operations. Note that even though this error message is the most common in this situation (since, well, multiplication is pretty popular) there are similar messages for the misuse of ^,   /, and  \   as opposed to .^, ./, and   .\.

2. Index exceeds matrix dimensions.

Quite simply, this error arises when you try to reference an element that doesn’t exist. For example, if the matrix has N elements, and you try to index into the N+1 element:

A = magic(5)
A =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

A(26)
Index exceeds matrix dimensions.

To fix this error, double-check that the matrix is the size you were expecting it to be and that the index you’re using is also what you expect. For example, if the index is the result of a calculation or is part of a loop, then you might need to adjust the calculation of the number of loop iterations. Some useful functions to check sizes and number of elements are numel(), size(), and length().

3. Subscript indices must either be real positive integers or logicals.

The most common reason this message arises is that people come to MATLAB from other programming languages and can’t get used to the fact that MATLAB indexing begins at 1. A(1) is the first element in a vector or matrix (or equivalently A(1,1)), not A(0) like in other programming languages!

A = magic(3)
A =

     8     1     6
     3     5     7
     4     9     2

A(0)
Subscript indices must either be real positive integers or logicals.

There are a number of theories for why MATLAB uses 1-based indexing, but ultimately the answer is pretty simple. 1-based indexing is the language of Mathematics, as confirmed by Cleve Moler himself in a comment on this April Fools blog post.

We have always had BOTH 0-based indexing and 1-based indexing. In order to distinguish between the two, 0-based indices are followed by “+1″. The 1-based indices are preferred becaused they are the language of mathematics. — Cleve

I won’t expound on this anymore, but suffice it to say if you’re interested in this, a quick google search will turn up bountiful results, as it has a long and contentious history!

This error message can also arise if you use a noninteger (or negative) value to index. What is MATLAB supposed to do with A(1.5) or A(-3)? In this context, it’s again likely that you’ll want to check the bounds of any loop statements in your code to make sure they aren’t producing decimal or negative values for indexing.

4. The expression to the left of the equals sign is not a valid target for an assignment.

This error message arises because of misuse of the = and == operators. The = operator does an assignment, and the == operator does a logical test for equality. In the context of an if statement, for example, the if operator is expecting to see a logical condition to determine whether to continue executing code. So the following example code produces this error:

n = 5;
if n = 4
    n = n.^2;
end
 if n = 4
      |
Error: The expression to the left of the equals sign is not a valid target for an assignment.

To fix this all you need to do is use == instead:

n = 5;
if n == 4
    n = n.^2;
end

This code outlines the differences between the two operators more clearly:

A = 1:5
A =

     1     2     3     4     5

B = 5;
A == B
ans =

     0     0     0     0     1

C = A == B
C =

     0     0     0     0     1

In short: when you need to compare values, use ==. When you want to assign a value, use =.

5. Subscripted assignment dimension mismatch.

This error message arises because of an attempt to assign a vector or matrix into a compartment that it does not fit in. The dimension of the subscripted elements does not match the dimension of the assignment. For example, you cannot assign the first element in a matrix to be a vector, because there is only room for 1 element:

A = magic(3)
A =

     8     1     6
     3     5     7
     4     9     2

A(1) = [4 5 6]
Subscripted assignment dimension mismatch.

This error can be much more subtle when you’re working with large matrices or loops, and it can occur because of a mismatch on either side of the equals sign. Sometimes the size of a vector or matrix can grow in an unexpected way in a loop, and you’ll receive this message and wonder what went wrong. The best way to debug this error is to double-check that all of your assignments are the sizes you expect them to be and that your matrices are growing (or not) as you expect them to.

If you don’t have any loops, just break the statement apart and check the size of each side. You won’t get this error if the sizes match exactly:

size(A(1:3))
ans =

     1     3

size([4 5 6])
ans =

     1     3

A(1:3) = [4 5 6]
A =

     4     1     6
     5     5     7
     6     9     2

Feedback

Obviously, I could go on with another 25 error messages, but I think these are the most common ones I see people posting about. If you’re interested in reading about some others, check out this link:

http://en.wikibooks.org/wiki/MATLAB_Programming/Error_Messages

Post about your favorite or least favorite MATLAB error messages in the comments, and let me know what you think!

Disclaimer: All views and/or opinions expressed in this post are my own, and should not be interpreted in any other way.

subscripted assignment dimension mismatch

Hi everyone, any help on this will be highly appreciated!!

Here is my program:

fid = fopen('test.cal');

[paramlist l] = textscan(fid, '%s %s %s %s %s'); %paramlist is a variable

fclose(fid);

[len wid] = size(paramlist{1}); %len=3, wid=4

chanlist = zeros(3,4); %chanlist is a variable

chanlist(1,1:4) = [paramlist{2}{1},paramlist{3}{1},paramlist{4}{1},paramlist{5}{1}]; %write the info from the test.cal into the 1st row of matrix, chanlist. Error happen due to this line.

Here is the «test.cal» file:

channel DIGOUT 0 0 shutter1

channel DIGOUT 0 1 shutter2

channel DIGOUT 0 2 shutter3

When I run the program, the error «subscripted assignment dimension mismatch» will show up, I really dont know how resolve it.

Related Question

    Понравилась статья? Поделить с друзьями:
  • Subaru код ошибки p0021
  • Subscript out of range ошибка при импорте
  • Subaru p1400 ошибка
  • Subscript out of range vba excel ошибка
  • Subscript out of bounds ошибка