MATLAB Answers

How to save all variables in for loop

2 views (last 30 days)
Hamed Bolandi
Hamed Bolandi on 24 Jun 2021
Edited: Hamed Bolandi on 25 Jun 2021
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

Answers (2)

Alan Stevens
Alan Stevens on 24 Jun 2021
Try
load(i,:)=com(i,1)*sin(com(i,2)*t);
  1 Comment
Hamed Bolandi
Hamed Bolandi on 24 Jun 2021
Just last iteration got value, others are zero.

Sign in to comment.


Steven Lord
Steven Lord on 24 Jun 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);
You shouldn't name your variable load as that already has a meaning in MATLAB.
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 Comment
Hamed Bolandi
Hamed Bolandi on 25 Jun 2021
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

Sign in to comment.

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by