How to save all variables in for loop

조회 수: 2(최근 30일)
Hamed Bolandi 2021년 6월 24일
편집: Hamed Bolandi 2021년 6월 25일
I am trying to make a for loop that each iteration gereates a sine wave equation and want to save all 30 iterations in an array. I tried the code below but raised with error "Unable to perform assignment because the indices on the left side are not compatible with the size of the right side"
clc
clear
dt = 1;
total_time = dt*10;
t = 0:dt:total_time;
A = [1000,2000,3000,4000,5000];
W= [0.5,1,2,3,4,5];
[m,n] = ndgrid(A,W);
com = [m(:),n(:)];
for i=length(com)
figure
end

댓글을 달려면 로그인하십시오.

답변(2개)

Alan Stevens 2021년 6월 24일
Try
댓글 수: 1표시숨기기 없음
Hamed Bolandi 2021년 6월 24일
Just last iteration got value, others are zero.

댓글을 달려면 로그인하십시오.

Steven Lord 2021년 6월 24일
There are a few problems or concerns about the code you've posted.
for i=length(com)
This for loop body will execute exactly once. It will not execute once per element of com (unless com were a scalar, which it's not.) In addition, since com is a matrix length may not do what you expect. If you want this to run once per row of com use height instead of length or use size(com, 1). If you want this to run once per element use numel.
Since i is a scalar, load(i) refers to exactly one element of the variable.
Both com(i, 1) and com(i, 2) are also scalar, but t is not. Therefore the expression on the right side of the equals sign has the same number of elements as t does.
Can you fit (for example) a dozen eggs into a single cup of an egg carton (without scrambling them)? That's what your code is trying to do. Instead, make the left side of the equals sign refer to the same number of elements as the right, perhaps (since t is a row vector) making the left side a matrix and assigning to a row of that matrix like the following:
M = zeros(3, 3)
M(1, :) = [4, 8, 15] % M(1, :) refers to 3 elements of M. [4, 8, 15] has 3 elements.
M(3, :) = [16, 23, 42]
댓글 수: 1표시숨기기 없음
Hamed Bolandi 2021년 6월 25일
Thanks for comprehensive asnwer. it worked as below:
l=zeros(30,11);
for i=1:30
l(i,:)=com(i,1)*sin(com(i,2)*t);
end

댓글을 달려면 로그인하십시오.

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by