How to save all variables in for loop
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Steven Lord
il 24 Giu 2021
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]
1 Commento
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!