How to save all variables in for loop
4 次查看(过去 30 天)
显示 更早的评论
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(:)];
% load=com(1,1)*sin(com(1,2)*t);
for i=length(com)
load(i)=com(i,1)*sin(com(i,2)*t);
figure
plot(load);
end
0 个评论
回答(2 个)
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.
load(i)=com(i,1)*sin(com(i,2)*t);
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]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!